标题: 【上海校区】浅析setTimeout与Promise [打印本页] 作者: 不二晨 时间: 2018-8-13 09:35 标题: 【上海校区】浅析setTimeout与Promise 前言我们先看一到常见的前端面试题:
var p1 = new Promise(function(resolve, reject){ resolve(1);})setTimeout(function(){ console.log("will be executed at the top of the next Event Loop");},0)p1.then(function(value){ console.log("p1 fulfilled");})setTimeout(function(){ console.log("will be executed at the bottom of the next Event Loop");},0)复制代码上例代码执行输出顺序如何?这道题也是本文创作的源泉,其答案是:
p1 fulfilledwill be executed at the top of the next Event Loopwill be executed at the bottom of the next Event Loop复制代码接下来展开解释输出结果原因,看完本文应该能了解setTimeout和Promise的区别。 事件循环事件循环相关详细内容在JavaScript异步编程一文已经介绍过,本文不再赘述,进行一些补充和总结:
回顾介绍基本结束,我们以一个题目再次回顾一下内容:
setTimeout(function(){ console.log("will be executed at the top of the next Event Loop")},0)var p1 = new Promise(function(resolve, reject){ setTimeout(() => { resolve(1); }, 0);});setTimeout(function(){ console.log("will be executed at the bottom of the next Event Loop")},0)for (var i = 0; i < 100; i++) { (function(j){ p1.then(function(value){ console.log("promise then - " + j) }); })(i)}复制代码代码输出结果是什么呢?快点确认一下吧:
will be executed at the top of the next Event Looppromise then - 0promise then - 1promise then - 2...promise then - 99will be executed at the bottom of the next Event Loop复制代码