Async和Await

2018-10-19  本文已影响0人  梦里coding

1、概述

async(异步) 函数变体

以下是已经存在的异步函数变体。请注意无处不在的 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 返回:

    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);
    });
    }
上一篇 下一篇

猜你喜欢

热点阅读