Open yiqia opened 3 years ago
/**
*/
async function async1() {
console.log('async1 start');
await async2().then(res => console.log(res));
console.log('async1 end');
}
async function async2() {
console.log('async2');
return 123;
}
console.log('script start');
setTimeout(function () {
console.log('setTimeout');
}, 0);
async1();
new Promise(function (resolve) {
console.log('promise1');
resolve();
}).then(function () {
console.log('promise2');
});
console.log('script end');
打印的结果以及为什么顺序是这样
建议添加一下代码包裹,方便读者阅读 @yiqia
建议添加一下代码包裹,方便读者阅读 @yiqia
不太理解async1 end比promise 2先放进微队列,为啥promise 2先输出
@GdgmPhs 你可以这么理解,await 语句创建并返回了一个promise,await 后面的代码相当于then()的回调函数
async function async1() {
console.log('2 async1 start');
// await async2().then(res => console.log(res));
// console.log('async1 end');
// 相当于以下代码
new Promise((resolve) => {
async2()
resolve(123)
}).then((res) => {
console.log('6 ' + res)
})
.then(() => {
console.log('8 async1 end')
})
}
async function async2() {
console.log('3 async2');
return 123;
}
console.log('1 script start');
setTimeout(function () {
console.log('9 setTimeout');
}, 0);
async1();
new Promise(function (resolve) {
console.log('4 promise1');
resolve();
}).then(function () {
console.log('7 promise2');
});
console.log('5 script end');
async function async1() { console.log('async1 start') await async2().then(res=>console.log(res)) console.log('async1 end') } async function async2() { console.log('async2') return 123 } console.log('script start') setTimeout(function () { console.log('setTimeout') }, 0) async1() new Promise(function (resolve) { console.log('promise1') resolve() }).then(function () { console.log('promise2') }) console.log('script end')
打印的结果以及为什么顺序是这样