event loop原理,宏微任务,node和浏览器在实现loop时候的差别

  • 关于事件循环和宏任务微任务,这篇文章中讲的很清晰:

https://blog.csdn.net/Liu_yunzhao/article/details/90734257

文中提到一段代码的执行顺序

console.log("script start");

new Promise(function (resolve) {
  console.log("promise1");
  resolve();
}).then(function () {
  console.log("promise1-then");
});

setTimeout(function () {
  console.log("settimeout1");
}, 0);

async function async1() {
  console.log("async1 start");
  let resulet = await async2();
  console.log(resulet);
  console.log("async1 end");
}

async function async2() {
  console.log('async2');
  return "async2 return"
}

setTimeout(function () {
  console.log("settimeout2");
}, 0);

async1();

new Promise(function (resolve) {
  console.log("promise2");
  resolve();
}).then(function () {
  console.log("promise2-then");
});

console.log('script end');

在node中和浏览器中有所不同:
// nodejs

script start
promise1
async1 start
async2
promise2
script end
promise1-then
promise2-then
async2 return
async1 end
settimeout1
settimeout2

// chrome

script start
VM7991:4 promise1
VM7991:15 async1 start
VM7991:22 async2
VM7991:33 promise2
VM7991:39 script end
VM7991:7 promise1-then
VM7991:17 async2 return
VM7991:18 async1 end
VM7991:36 promise2-then
undefined
VM7991:11 settimeout1
VM7991:27 settimeout2

可以看到async的顺序不同,关于这个问题,主要是由于新旧版本v8优化方式的不同,具体可见这篇文章:
https://www.zhihu.com/question/268007969/answer/341146726
总的老说就是如果在async2中的console前也加上await两个场景的结果就一样了

你可能感兴趣的:(javascript)