Async和Await

1、概述

async(异步) 函数变体

以下是已经存在的异步函数变体。请注意无处不在的 async 关键字。

  • 异步函数声明: async function foo() {}
  • 异步函数表达式: const foo = async function () {};
  • 异步函数定义:let obj = { async foo() {} }
  • 异步箭头函数: const foo = async () => {};

async(异步) 函数总是返回 Promises

async(异步) 函数的 Promise 完成状态:

    async function asyncFunc() {
    return 123;
    }
    asyncFunc()
    .then(x => console.log(x));
    // 123

async(异步) 函数的 Promise 拒绝状态:

    async function asyncFunc() {
    throw new Error('Problem!');
    }
    asyncFunc()
    .catch(err => console.log(err));
    // Error: Problem!

通过 await 处理 async(异步) 计算的结果和错误

await(只允许在 async(异步) 函数内部使用)等待其操作对象 Promise 返回:

  • 如果 Promise 是完成状态,await 的结果是完成态的值。
  • 如果 Promise 是拒绝状态,await 会抛出拒绝值。
    处理单个 async(异步) 返回值:
    async function asyncFunc() {
    const result = await otherAsyncFunc();
    console.log(result);
    }
    // 等价于:
    function asyncFunc() {
    return otherAsyncFunc()
    .then(result => {
    console.log(result);
    });
    }

按顺序处理多个 async(异步) 返回值:

    async function asyncFunc() {
    const result1 = await otherAsyncFunc1();
    console.log(result1);
    const result2 = await otherAsyncFunc2();
    console.log(result2);
    }
    // 等价于:
    function asyncFunc() {
    return otherAsyncFunc1()
    .then(result1 => {
    console.log(result1);
    return otherAsyncFunc2();
    })
    .then(result2 => {
    console.log(result2);
    });
    }

并行处理多个 async(异步) 返回值:

    async function asyncFunc() {
    const [result1, result2] = await Promise.all([
    otherAsyncFunc1(),
    otherAsyncFunc2(),
    ]);
    console.log(result1, result2);
    }
    // 等价于:
    function asyncFunc() {
    return Promise.all([
    otherAsyncFunc1(),
    otherAsyncFunc2(),
    ])
    .then([result1, result2] => {
    console.log(result1, result2);
    });
    }

你可能感兴趣的:(Async和Await)