我有以下代码:
var incr = num => new Promise(resolve => {
resolve(num + 1);
});
var x = incr(3)
.then(resp => incr(resp))
.then(resp => console.log(resp));
async function incrTwice(num) {
const first = await incr(num);
const twice = await incr(first);
console.log(twice);
}
incrTwice(6);Run Code Online (Sandbox Code Playgroud)
我相信(可能是错误的)显示了实现相同功能的两种等效方法:首先通过链接承诺,其次使用 async/await 的语法糖。
我希望promise 链接解决方案首先是console.log,然后是异步函数,但是异步函数console.log 的第一个然后是promise 链接解决方案打印。
我的逻辑如下:
xs 初始解析将在处理声明时首先出现在微任务队列中x和的声明之间堆栈是空的,incrTwice这将导致微任务队列被刷新(导致承诺链的完成)
incrTwice 被定义为incrTwice在awaits处的微任务队列上执行排队,最终打印到控制台
显然我在某处有误解,有人能够指出我错在哪里吗?