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

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函数的返回值(或者抛出异常)。

 

posted @ 2018-06-03 12:04 harelion 阅读(...) 评论(...) 编辑 收藏