共计 1212 个字符,预计需要花费 4 分钟才能阅读完成。
- 对于事件循环和宏工作微工作,这篇文章中讲的很清晰:
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
2020-08-26