4

一个关于宏任务微任务的题目,你"绝对"猜不到答案

 2 years ago
source link: https://zhuanlan.zhihu.com/p/449183802
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

一个关于宏任务微任务的题目,你"绝对"猜不到答案

在饥人谷学前端、Java、C++。 咨询见个人简介

这是一个关于Promise 微任务的题目,猜猜以下代码输出是什么?为什么?

let p1 = Promise.resolve()
  .then(v => console.log(1))
  .then(v => console.log(2))
  .then(v => console.log(3))
 
p1.then(v => console.log(4))
p1.then(v => console.log(5))
 
let p2 = Promise.resolve()
  .then(v => console.log(11))
  .then(v => console.log(22))
  .then(v => console.log(33))
 
p2.then(v => console.log(44))
p2.then(v => console.log(55))

上面的题目发散自一个大厂的面试题

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')

可以在评论区或者 https://xiedaimala.com/bbs/topics/570#/ 晒自己的解题思路。如果需要,我也可以写篇文章细细讲解。点


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK