JavaScript async、await简化 Promise

说明

async、await 是一对关键字,简化 Promise 的写法,让异步代码,执行起来,与同步代码类似,更易于理解和维护

  • async关键字用于声明一个函数是异步的
  • await关键字用于等待一个异步操作的完成

Promise 传统写法

详见:https://www.malaoshi.top/show_1IX3oXyazfeK.html

两个异步代码,按照指定顺序执行,思路:

  • 将一个异步代码,放到函数 t() 中,该函数返回 Promise 对象

  • 将另一个异步代码,放到函数 my() 中的 then() 中

function t(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(111)
            resolve('AAA') // AAA会传给 then 中的 data
        },1000);
    });
}
function my(){
    t().then(function(data){
        setTimeout(function(){
            console.log(222,data) 
        },500)
    })
}

调用执行:

my()

缺点:复杂,代码量大

async、await新写法

await 用法

在当函数返回 Promise 时,就用 await 修饰,简化 then 代码块

注意: await 只能处理 resolve() 成功

async 修饰函数

当函数内部有 await 关键字时,该函数要有 async 修饰

改动上面的 my() 函数

  1. 由于 my() 函数内部,调用了 t() 函数,t() 函数返回 Promise,所以使用 await 修改 t() 函数

  2. 由于 my() 函数内部有 await 关键字,所以用 async 修改 my() 函数

普通函数实现

async function my(){
    const res = await t()

    setTimeout(function(){
         console.log(222,res)
    },500)
}

箭头函数实现

const my = async () => {
    const res = await t()
    console.log("res:",res)

    setTimeout(function(){
        console.log(222,res)
    },500)
}

调用

my()

async 函数的返回值

async 修饰的函数,该函数一定会返回 Promise 对象,即使返回普通值,也会自动封装成 Promise 对象

async function testAsync() {
 return "hello async";
}

const result = testAsync();
console.log(result);

错误处理

上面的 t() 函数中可能报错 或 执行失败,在 my() 函数中,有以下处理方式

t()改动

function t(){
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log(111)
            // resolve('AAA') // AAA会传给 then 中的 data
            reject('测试错误') // 表示执行失败
        },1000);
    });
}

处理错误方式一

Promise的 reject() 方法被调用,await 关键字将reject() 转换为一个可捕捉的错误,然后使用 try ... catch 捕获并处理

const my = async () => {
    try{
        const res = await t()
        console.log("res:",res)
        setTimeout(function(){
            console.log(222,res)
        },500)
    }catch(err){
        console.error("my() 中捕获错误:",err)
    }
}
my()

执行结果:

111
my() 中捕获错误: 测试错误

处理错误方式二

返回 Promise 的函数,可以直接写 .catch( callback ) 捕获异常

const my = async () => {
    const res = await t().catch( err => {
        console.error("my() 中捕获错误:",err)
    })
    if(res){
        console.log("res:",res)
        setTimeout(function(){
            console.log(222,res)
        },500)
    }
}
my()

参考:
https://segmentfault.com/a/1190000044032778


原文出处:/show_1IX8X09VS2hV.html