async...await中使用使用Promise对象的一些注意问题

await后可以跟一个异步表达式(如promise的表达式),也可以跟一个普通的表达式(如:console.log(123))

例子1:如果await紧跟一个没有resolve的promise对象,则后续的代码不会被执行。如:

async function a(){
    // 如果await后是promise对象 
    await new Promise(resolve => {
        console.log(66666)
    })
    console.log(1)
}
a();
Promise.resolve().then(()=>{
    console.log(3)
})

运行结果:

运行结果:
    66666
    3

这里要注意,console.log(1)并不会被执行,这是因为

async function a(){
    // 如果await紧跟一个普通表达式
    await console.log(1);
    console.log(2)
}

相当于

async function a(){
    new Promise(resolve => {
        console.log(1)
    }).then(() => {
        console.log(2)
    })
}

由于没有Promise状态没有resolved,因此不会执行后续.then的代码。

运行过程示意图:

例子2:如果await紧跟一个已经resolved的Promise对象 

async function a(){
    // 如果await紧跟一个已经resolved的promise对象 
    await new Promise(resolve => {
        resolve();
        console.log(66666)
    })
    console.log(1)
}
a();
Promise.resolve().then(()=>{
    console.log(3)
})

运行结果:

运行结果:
    66666
    1
    3

运行过程示意图:

例子3:await后紧跟一个普通表达式

async function a(){
    // 如果await紧跟一个普通表达式
    await console.log(1);
    console.log(2)
}
a();
Promise.resolve().then(()=>{
    console.log(3)
})

运行结果:

运行结果:
    1
    2
    3

运行过程示意图:

例子4:一个较为复杂的例子

function c(){
    return new Promise((resolve)=>{
        console.log('开始了')
        resolve()
    }).then(()=> {
        console.log('c.......');
        return 65666
    }).then(res => {
        console.log(res);
        return '返回了一个值'
    })
}
async function a(){
    // 如果await后的表达式是一个promise对象 
    await c().then((res)=>{
        console.log('then....' + res)
    })
    console.log(1)
}
a();
console.log('同步代码')
Promise.resolve().then(()=>{
    console.log(3)
})

运行结果:

    '开始了'
    '同步代码'
    'c.......'
    3
    65666
    'then....返回了一个值'
    1

运行过程示意图:

例子9:

发布了47 篇原创文章 · 获赞 3 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/u010047432/article/details/104679231