async 函數promise
const promise = new Promise((resolve, reject)=>{ setTimeout(function(){ console.log("Done1"+"First"); resolve("Done1"+"First"); }, 1000); }); async function fn(){ console.log("開始執行!"); // 只能在 async 函數裏使用 await 123; // 只能在 async 函數裏使用 // 只能在 async 函數裏使用 await promise; // 異步等待,須包裝成 Promise 對象 console.log("執行完了!"); }; fn();
真正意義上去解決異步回調的問題,異步
同步流程 表達 異步操做async
本質上就是: Generator 的語法糖函數
等待異步操做spa
只會 等待 初始化狀態的 Promise 實例(若是是失敗狀態,會報錯)code
const promise = new Promise((resolve, reject)=>{ setTimeout(function(){ resolve("1"); }, 1000); }); async function fn(){ console.log('開始執行'); const result1 = await promise; console.log(result1); const result2 = await new Promise((resolve, reject)=>{ setTimeout(function(){ resolve('2'); // 若是這裏 reject() 則下面的代碼都不會執行了 }, 2000); }); const result3 = await new Promise((resolve, reject)=>{ setTimeout(function(){ resolve('3'); }, 3000); }); }; var ret = fn(); console.log(ret); // 默認返回值 就是Promise 實例 ret.then(result=>{ console.log('所有都成功了'); console.log(result); // 若是沒有返回值,默認 unfefined }).catch(result=>{ // 必須是 await 修飾的 promise 實例,且必須 失敗狀態 console.log('Something is wrong!'); });