223、async函式及其內部的await指令
阿新 • • 發佈:2020-08-05
async函式及其內部的await指令 (1)async函式可以包含await指令,該指令會暫停原非同步函式的執行,並等待右側Promise返回結果; (2)若 Promise 正常處理,其回撥resolve函式的引數作為 await 表示式的值; 示例一: function thisPromise(x) { return new Promise(function(resolve){ setTimeout(function(){ resolve(x); }, 500); }); }; async function thisAdd(x) { //左側寫法一 vara = await thisPromise(20); //此前有await var b = await thisPromise(30); //此前有await return x + a + b; } thisAdd(10).then(function (v){ console.log(v); //1 秒後列印 60 }); 示例二: function thatPromise(x) { return new Promise(function(resolve){ setTimeout(function(){ resolve(x); }, 500); }); }; varthatAdd = async function(x) { //左側寫法二 var a = thatPromise(20); //此前沒有await var b = thatPromise(30); //此前沒有await return x + a + b; } thatAdd(10).then(function (v){ console.log(v); //0.5 秒後列印 60 });