whynotgonow 2019-06-29
有一次在面试题中有做到promise与setTimeout的执行顺序,当时有点懵,执行顺序还是弄错了一点点,这里记录下
setTimeout(function() { console.log(111) }, 0); setTimeout(function() { console.log(333) }, 1000); new Promise(function(resolve){ console.log(444); resolve(); console.log(555); }).then(function(){ console.log(666); }); console.log(777); async function test1() { console.log("test1"); await test2(); console.log("test1 last"); } async function test2() { console.log("test2"); } test1();
参考了这篇文章的一些内容 参考文章
setImmediate(function(){ console.log(1); },0); setTimeout(function(){ console.log(2); },0); new Promise(function(resolve){ console.log(3); resolve(); console.log(4); }).then(function(){ console.log(5); }); console.log(6); process.nextTick(function(){ console.log(7); }); console.log(8);
macro-task: script (整体代码),setTimeout, setInterval, setImmediate, I/O, UI rendering. micro-task: process.nextTick, Promise(原生),Object.observe,MutationObserver
创建setImmediate macro-task 创建setTimeout macro-task 创建micro-task Promise.then 的回调,并执行script console.log(3); resolve(); console.log(4); 此时输出3和4,虽然resolve调用了,执行了但是整体代码还没执行完,无法进入Promise.then 流程。 console.log(6)输出6 process.nextTick 创建micro-task console.log(8) 输出8
优先级: promise.Trick()>promise的回调>setTimeout>setImmediate
正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯^_^)
往期好文推荐: