1. 程式人生 > >async/await工作機制探究--NodeJS

async/await工作機制探究--NodeJS

span 結果 函數 class fir RR rim require first

ES6中的async/await讓Promise變得更加簡便,通常await處理的鏈式Promise會包裹在函數中,返回結果仍然是一個Promise對象。

但是當await直接處理鏈式Promise時,編譯器是會返回一個Promise對象等待下次await,還是繼續執行Promise對象直到返回結果不再是Promise?

測試環境

NodeJS v8.7.0

測試代碼

 1 const util = require(‘util‘);
 2 
 3 const prom2 = util.promisify((a, b, cb) => {
 4     cb(null, a + b);
5 }); 6 7 function promiseCal(a, b) { 8 return prom2(a, b) 9 .then((val) => { 10 console.log(`value in first then: ${val}`); 11 return val * 2; 12 }) 13 .then((val) => { 14 console.log(`Value in second then: ${val}`); 15 return
val * 3 16 }); 17 } 18 19 async function test() { 20 // await getting value from chained promise 21 let val1 = await promiseCal(2, 4); 22 23 console.log(`Typeof val1: ${typeof val1}\nFinal returned value: ${val1}`); 24 25 // await getting value from another form 26 console.log(`[v2] Type of prom2: ${typeof
prom2}`); 27 let val2 = await prom2(4, 6) 28 .then((val) => { 29 console.log(`[v2] Value in first then: ${val}`); 30 return val * 2; 31 }) 32 .then((val) => { 33 console.log(`[v2] Value in second then: ${val}`); 34 return val * 3 35 }); 36 console.log(`[v2] Typeof val2: ${typeof val2}\n[v2] Final returned value: ${val2}`); 37 } 38 39 test() 40 .catch(e => console.error(e.stack || e));

運行結果

value in first then: 6
Value in second then: 12
Typeof val1: number
Final returned value: 36
[v2] Type of prom2: function
[v2] Value in first then: 10
[v2] Value in second then: 20
[v2] Typeof val2: number
[v2] Final returned value: 60

結論

await操作符會沿著Promise鏈處理到返回結果不再是Promise位置,await語句返回的將是Primise鏈上最後一個then函數的返回值(或者拋出異常)。

async/await工作機制探究--NodeJS