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

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

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

 

測試環境函數

NodeJS v8.7.0測試

 

測試代碼ui

 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));

 

運行結果spa

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

 

結論code

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

相關文章
相關標籤/搜索