async 和 await 理解

158 阅读2分钟

一、async

1.含义

  • ES2017 标准引入了 async 函数,使得异步操作变得更加方便。
    
  • async 函数是 Generator 函数的语法糖。
    
  • Generator 函数的改进
    
    • 内置执行器(函数的执行,与普通函数一模一样,)
      
    • 返回值是 Promise

2.基本用法

创建一个async函数:返回值为一个promise对象,默认为resolve状态

const asyncFun = async function() {
    return 100
}
asyncFun().then((res) => {
 console.log('res', res) // res 100
})
// `async`函数返回一个 Promise 对象,可以使用`then`方法添加回调函数。


const asyncFun = async function() {
    throw new Error('出错了, 404 啦');
}
// async函数内部抛出错误,会导致返回的 Promise 对象变为reject状态。
// 抛出的错误对象会被`catch`方法回调函数接收到。

二、await

1.含义

  • 正常情况下,await命令后面是一个 Promise 对象,返回该对象的结果。
  • 如果不是 Promise 对象,就直接返回对应的值。
  • 另一种情况是,await命令后面是一个thenable对象(即定义了then方法的对象),那么await会将其等同于 Promise 对象。
  • await命令后面的 Promise 对象如果变为reject状态,则reject的参数会被catch方法的回调函数接收到。
  • 任何一个await语句后面的 Promise 对象变为reject状态,那么整个async函数都会中断执行。

2.基本用法

const imitateAsyncFun = function(flag) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if(flag) {
                resolve({success: 'this is a 200'})
            } else {
                reject({error: 'this is a 404'});
            }
        }, 1000)
    })
}
let obj = {}
obj.then = (resolve, reject) => {
    resolve("111111111")
}
const asyncFun = async function() {
    const res =  await imitateAsyncFun(true);
    console.log('res', res) // res { success: 'this is a 200' }
    const objreuturn = await obj
    console.log('objreuturn', objreuturn); // objreuturn 111111111
    return {res, objreuturn}
    // const rej = await imitateAsyncFun(false)
    // console.log('rej', rej); // 不执行
}
asyncFun().then((res) => {
 console.log('res', res) // res { res: { success: 'this is a 200' }, objreuturn: '111111111' }
}).catch(error => {
    console.log('error_catch', error) // error_catch 111111111
})

三、错误处理

  • 如果await后面的异步操作出错,那么等同于async函数返回的 Promise 对象被reject
const asyncFun = async function() {
    await new Promise(function (resolve, reject) {
        throw new Error('出错了');
    });
}
asyncFun().then((res) => {
 console.log('res', res)
}).catch(error => {
    console.log('error_catch', error) // error_catch Error: 出错了
})
  • 处理错误
    • 放在try...catch结构里面
    • await后面的 Promise 对象再跟一个catch方法,处理前面可能出现的错误。
const asyncFun = async function() {
   try {
       await new Promise(function (resolve, reject) {
           throw new Error('出错了');
       });
   } catch (error) {
       
   }
  return  await imitateAsyncFun(true);
}
asyncFun().then((res) => {
console.log('res', res) // res { success: 'this is a 200' }
}).catch(error => {
   console.log('error_catch', error)
})
const asyncFun = async function() {
   await new Promise(function (resolve, reject) {
       throw new Error('出错了');
   }).catch(e => console.log(e) );
  return  await imitateAsyncFun(true);
}
asyncFun().then((res) => {
console.log('res', res)
}).catch(error => {
   console.log('error_catch', error)
})