【发布时间】:2018-02-14 08:17:30
【问题描述】:
我对这段代码的输出感到困惑。
输出为4 3 2 1
我如何理解流程?
new Promise(resolve => {
resolve(1);
Promise.resolve().then(() => console.log(2));
console.log(4);
}).then( t => console.log(t) );
console.log(3);
【问题讨论】:
-
同步代码保持同步,异步代码保持异步——你可以从输出中看到console.log的执行顺序
-
1, 2, 3(最多 .then),4, 5(最多 .then) 6,3(代码在 .then),5(代码在 .then) - 或者,请参阅jsfiddle.net/gzy6ncz3
-
您期望的输出是什么? this 回答中有视频和一些文档的链接,可以提供帮助。
-
想到
resolve()做类似setTimeout(later, 0)的事情,其中later是使用then注册的函数,这可能是一个很好的方法来推理正在发生的事情,不是吗?我的意思是说这是asynchronous。它被推送到事件循环对吗?
标签: javascript promise