场景一
function funOne(){
console.log(1)
}
async function funTwo() {
await funOne()
console.log(2)
}
funTwo()
console.log(3)
await阻碍了2的打印
场景二
function funOne(){
console.log(1)
return new Promise((resolve)=>{
resolve(4)
})
}
async function funTwo() {
await funOne()
console.log(2)
}
funTwo()
console.log(3)
await后面的函数返回一个promise对象,执行顺序跟场景一一样,也是await阻碍了后面的代码的执行,先执行async外边的
场景三
function funOne(){
console.log(1)
return new Promise((resolve)=>{
resolve(4)
})
}
async function funTwo() {
let res = await funOne()
console.log(2)
console.log(res)
}
funTwo()
console.log(3)
funOne虽然返回的是一个promise对象,但是res的到的确实promise的执行结果,也就是说res得到了resolve中的参数4,那就得看看场景四了
场景四
function funOne(){
console.log(1)
return new Promise((resolve,reject)=>{
reject('让res得到失败的结果')
})
}
async function funTwo() {
let res = await funOne()
console.log(2)
console.log(res)
}
funTwo()
console.log(3)
因为promise失败了,导致await后面的代码不执行了
场景五
function funOne(){
console.log(1)
return new Promise((resolve,reject)=>{
reject('让res得到失败的结果')
})
}
async function funTwo() {
try{
let res = await funOne()
console.log(2)
console.log(res)
}catch(err){
console.log('promise失败了',err)
}
}
funTwo()
console.log(3)
promise失败了,导致了2不会打印,燃鹅,失败的结果却被catch捕获了,所以给res赋值的时候,是拿不到失败的结果的
场景六
function funOne(){
return new Promise((resolve,reject)=>{
resolve('成功')
})
}
async function funTwo() {
try{
let res = await funOne()
}catch(err){
console.log('失败了',err)
}
}
console.log('结果:',funTwo())
funTwo().then(res=>{
console.log('结果2:',res)
}).catch(err=>{
console.log('结果3:',err)
})
虽然打印funTwo()时它是一个promise,但是在结果2:后确打印undefined,也就是通过funTwo是拿不到funTwo里面的promise的结果的,在继续看看场景七
场景七
function funOne(){
return new Promise((resolve,reject)=>{
resolve('成功')
})
}
async function funTwo() {
let res
try{
res = await funOne()
}catch(err){
console.log('失败了',err)
}
return res
}
console.log('结果:',funTwo())
funTwo().then(res=>{
console.log('结果2:',res)
}).catch(err=>{
console.log('结果3:',err)
})
现在可以打印结果2,因为funTwo中有return res
场景八
function funOne(){
return new Promise((resolve,reject)=>{
resolve('成功')
})
}
async function funTwo() {
let res
try{
res = await funOne()
console.log(res,'res到底是promise的resolve中的“成功”二字')
}catch(err){
console.log('失败了',err)
}
return res
}
console.log('结果:',funTwo())//res是promise
惊不惊喜,意不意外,promise受await的影响变为了resolve中的结果,
而funTwo中的res受async的影响确变为了promise,进一步实验来证明一下这个说法,看场景九
场景九
async function funTwo() {
let res = await new Promise((resolve,reject)=>{
resolve('成功')
})
console.log(res)
return res
}
console.log(funTwo())
是不是,场景九应证了场景八的说法
场景十
![!](https://img-blog.csdnimg.cn/20210410221427445.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTI1NDM0NQ==,size_16,color_FFFFFF,t_70)
③被await阻塞了,燃鹅①和②确比③更晚执行,同时也发现,因为resolve,所以打印了1111
因为失败了,所以③不执行,被await塞死了