题目3
let res = function () {
console.log(1);
return new Promise((resolve, reject) => {
console.log(2);
resolve(4);
})
}
new Promise(async (resolve, reject) => {
console.log(3);
let test = await res();
console.log(test);
})
console.log(5);
new Promise((resolve, reject) => {
console.log(6);
});
console.log(7);
分析
time 2m
let res = function () {
console.log(1);
return new Promise((resolve, reject) => {
console.log(2);
resolve(4);
})
}
new Promise(async (resolve, reject) => {
console.log(3);
//promise1
let test = await res();
/**
* await res()
*相当于res()运行,之后then
* res().then((res)=>{
* console.log(test);
* })
*/
console.log(test);
})
console.log(5);
new Promise((resolve, reject) => {
console.log(6);
});
console.log(7);
async function test(){
}
console.log(test())
test()运行返回promise
async function test(){}相当于new Promise()
await test()相相当于test().then,test()返回promise,相当于promise.then(),类似于下面代码
let test = await res();
/**
* await res()
*相当于res()运行,之后then
* res().then((res)=>{
* console.log(test);
* })
*/
可以分析成、等价于以下代码
;(function () {
console.log(1);
return new Promise((resolve, reject) => {
console.log(2);
resolve(4);
})
})().then();
new Promise((resolve, reject) => {
console.log(2);
resolve(4);
}).then()
执行栈
script
function ->res 这只是res赋值为函数,但没有运行
3 new promise回调函数虽然是async,但是里面是同步代码,await有区别
1 运行res(),打印1
2
5
6
7
promise1.then cb ->4
宏任务
微任务
promise1
promise1.then cb x
变形1
time 8m53s
let res = function () {
console.log(1);
return new Promise((resolve, reject) => {
setTimeout(() => {
new Promise((resolve) => {
console.log(2);
setTimeout(() => {
console.log(3)
})
})
}, 0)
resolve(5);
})
}
new Promise(async (resolve, reject) => {
setTimeout(() => {
Promise.resolve().then(() => {
console.log(4);
})
}, 0);
//promise1
let test = await res();
/**
* await res()
*
* res().then((res)=>{
* console.log(test);
* })
*/
console.log(test);
})
setTimeout(() => {
console.log(6);
}, 0)
new Promise((resolve, reject) => {
setTimeout(() => {
console.log(7);
})
}, 0);
console.log(8);
分析
先标注上setTimeout、promise,可以不标序号,分析时再标记,现在标记,省得分析时候忘记了
let res = function () {
console.log(1);
return new Promise((resolve, reject) => {
//setTimeout
setTimeout(() => {
new Promise((resolve) => {
console.log(2);
//setTimeout
setTimeout(() => {
console.log(3)
})
})
}, 0)
resolve(5);
})
}
new Promise(async (resolve, reject) => {
//setTimeout
setTimeout(() => {
//promise
Promise.resolve().then(() => {
console.log(4);
})
}, 0);
//promise
let test = await res();
console.log(test);
})
//setTimeout
setTimeout(() => {
console.log(6);
}, 0)
new Promise((resolve, reject) => {
//setTimeout
setTimeout(() => {
console.log(7);
})
}, 0);
console.log(8);
在setTimeout后面标注序号,省得之后忘记了
写awaitPromise与promise都可以
awaitPromise.then cb与promise.then都可以,做好加数字序号,可能太麻烦了
这道题与上面的题目意思差不多,但步骤很多,步骤多就容易犯错、失误,得精神集中
执行栈
微任务
宏任务