Async Functions (异步函数)

async(异步) 函数变体

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

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

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

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

JavaScript 代码:
  1. async function asyncFunc() {
  2. return 123;
  3. }
  4. asyncFunc()
  5. .then(x => console.log(x));
  6. // 123

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

JavaScript 代码:
  1. async function asyncFunc() {
  2. throw new Error('Problem!');
  3. }
  4. asyncFunc()
  5. .catch(err => console.log(err));
  6. // Error: Problem!

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

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

  • 如果 Promise 是完成状态,await 的结果是完成态的值。
  • 如果 Promise 是拒绝状态,await 会抛出拒绝值。

处理单个 async(异步) 返回值:

JavaScript 代码:
  1. async function asyncFunc() {
  2. const result = await otherAsyncFunc();
  3. console.log(result);
  4. }
  5. // 等价于:
  6. function asyncFunc() {
  7. return otherAsyncFunc()
  8. .then(result => {
  9. console.log(result);
  10. });
  11. }

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

JavaScript 代码:
  1. async function asyncFunc() {
  2. const result1 = await otherAsyncFunc1();
  3. console.log(result1);
  4. const result2 = await otherAsyncFunc2();
  5. console.log(result2);
  6. }
  7. // 等价于:
  8. function asyncFunc() {
  9. return otherAsyncFunc1()
  10. .then(result1 => {
  11. console.log(result1);
  12. return otherAsyncFunc2();
  13. })
  14. .then(result2 => {
  15. console.log(result2);
  16. });
  17. }

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

JavaScript 代码:
  1. async function asyncFunc() {
  2. const [result1, result2] = await Promise.all([
  3. otherAsyncFunc1(),
  4. otherAsyncFunc2(),
  5. ]);
  6. console.log(result1, result2);
  7. }
  8. // 等价于:
  9. function asyncFunc() {
  10. return Promise.all([
  11. otherAsyncFunc1(),
  12. otherAsyncFunc2(),
  13. ])
  14. .then([result1, result2] => {
  15. console.log(result1, result2);
  16. });
  17. }

错误处理:

JavaScript 代码:
  1. async function asyncFunc() {
  2. try {
  3. await otherAsyncFunc();
  4. } catch (err) {
  5. console.error(err);
  6. }
  7. }
  8. // 等价于:
  9. function asyncFunc() {
  10. return otherAsyncFunc()
  11. .catch(err => {
  12. console.error(err);
  13. });
  14. }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值