<
>

Javascript中Microtask和Macrotask鲜为人知的知识点

2022-04-18 11:56:55 来源:易采站长站 作者:

首先我们来看一道题目,如下javascript代码,执行后会在控制台打印出什么内容?

async function async1() {   console.log('async1 start');   await async2();   console.log('async1 end'); } async function async2() {   console.log('async2 start');   return new Promise((resolve, reject) => {     resolve();     console.log('async2 promise');   }) } console.log('script start'); setTimeout(function() {   console.log('setTimeout'); }, 0);   async1(); new Promise(function(resolve) {   console.log('promise1');   resolve(); }).then(function() {   console.log('promise2'); }).then(function() {   console.log('promise3'); }); console.log('script end')

说实话,真正能在面试中把这道题目答对的前端工程师凤毛麟角。我们先来瞧一下答案吧。把以上代码存到test.js文件中,并用node执行一下,结果如下:

Javascript中Microtask和Macrotask鲜为人知的知识点

如果把以上代码贴到一个网页中的script标签里面,然后打开这个网页,再打开控制台,可以看到如下输出(Chrome 64位 63.0.3239.84):

Javascript中Microtask和Macrotask鲜为人知的知识点

结果和node打印的一模一样。那么为'); resolve(); console.log('2222');}); 写法2:new Promise((resolve, reject) => { console.log('1111'); console.log('2222'); resolve();});

另外,对于Promise的链式调用,如new Promise(.https://www.easck.com/...).then(...).then(...)....,一次只放第一个then的内容进入Microtask,等第一个then执行的时候,会把第二个then放入Microtask,而不是一次把两个then都放进去。

以上就是javascript中Microtask和Macrotask鲜为人知的知识点的详细内容,更多关于Javascript中Microtask和Macrotask的资料请关注我们其它相关文章!

暂时禁止评论

微信扫一扫

易采站长站微信账号