promise對象的使用主要是解決一些函數的異步操做。php
function createPromise(funcName) { return new Promise((resolve, reject)=> { funcName(resolve, reject); console.log(111); }); } function nextPromise(funcName) { createPromise(funcName).then(()=>{ setTimeout(()=>{ console.log(555); }, 2000); console.log(333); }).then(()=>{ console.log(444); }).catch((err)=>{ console.log(err); }) } function getData(resolve, reject) { $.getJSON('https://www.runoob.com/try/ajax/jsonp.php?jsoncallback=?', function(data, status) { if (status === 'success') { console.log(data); console.log(222); resolve(); }else { reject(); } }) } nextPromise(getData);
最後結果爲ajax
111 ["customername1", "customername2"] 222 333 444 555