async和await_注意事项

1.await 必须用在async修饰的函数内

// 1. await必须用在被async修饰的函数内, 函数内无await, 则async可省略
// 报错: await is only valid in async functions
function myFn() {
    const res = await 1
}
myFn()

2.async修饰后, 此函数为异步函数

 // 在此函数内, 遇到await会暂停代码往下, 但不影响外面继续执行同步流程
// 等所有主线程同步代码走完, 再执行await并继续向下
console.log(1);
async function myFn() {
    console.log(2);
    const res = await 3
    console.log(res);
    console.log(4);
}
console.log(5);
myFn()
console.log(6);

3.await之后一般跟promise 

await后面一般跟Promise对象
// 如果跟的是非Promise对象, 则等待所有同步代码执行后, 把此结果作为成功的结果留在原地使用
// 如果是Promise对象, 则等待Promise对象内触发resolve返回成功结果, 在原地使用
let p = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(1)
    }, 2000)
})

console.log(1);
async function myFn() {
    console.log(2);
    const res = await p
    console.log(res);
    console.log(4);
}
console.log(5);
myFn()
console.log(6);

4.await不能捕获失败结果, 需要使用try+catch关键字捕获

/*
    try和catch语法
    try {
        // 这里放可能在执行中报错的代码
        // 如果报错会终止代码继续执行, 直接跳转进catch里执行
    } catch (err) {
        // err接收try大括号内报错抛出的异常代码
    }

*/
let p = new Promise((resolve, reject) => {
    setTimeout(() => {
        // resolve(1)
        reject(new Error('失败'))
    }, 2000)
})

async function myFn() {
    try {
        const res = await p
        console.log(res);
    } catch (err) {
        console.error(err)
    }
}
myFn()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值