await、return 和 return await 的陷阱

dev-reading/fe 是一个阅读、导读、速读的 repo,不要依赖于 dev-reading/fe 学习知识。本 repo 只是一个快速了解文章内容的工具,并不提供全文解读和翻译。你能够经过本平台快速了解文章里面的内容,找到感兴趣的文章,而后去阅读全文。javascript

本文讨论地址:https://github.com/dev-readin...java

阅读时间大概 2 分钟git


awaitreturnreturn await 有不少容易被忽视的不一样之处。github

首先定义一个异步函数:dom

async function waitAndMaybeReject() {
  // 等待1秒
  await new Promise(r => setTimeout(r, 1000));

  const isHeads = Boolean(Math.round(Math.random()));

  if (isHeads) {
    return 'yay';
  } else {
    throw Error('Boo!');
  }
}

函数等待 1 秒钟,而后有一半的几率返回 "yay",一半的几率抛出异常。异步

1 直接调用 Just calling

async function foo() {
  try {
    waitAndMaybeReject();
  }
  catch (e) {
    return 'caught';
  }
}

直接调用 foo,函数老是返回 Promise fulfill with undefined, without waitingasync

永远不会返回 "yay"函数

2 Awaiting

async function foo() {
  try {
    await waitAndMaybeReject();
  }
  catch (e) {
    return 'caught';
  }
}

调用 foo,函数返回的 Promise 等待 1 秒,而后 fulfill with undefined, or fulfill with "caught"工具

由于咱们 await waitAndMaybeReject() 的结果,若是 rejected,咱们的 catch 块捕获了异常,而后 "caught",若是 fulfilled,咱们的函数并无返回 Promise 的值。学习

3 Returning

async function foo() {
  try {
    return waitAndMaybeReject();
  }
  catch (e) {
    return 'caught';
  }
}

调用 foo,函数返回的 Promise 等待 1 秒,而后 fulfill with "yay", or reject with Error('Boo!')

4 Return-awaiting

async function foo() {
  try {
    return await waitAndMaybeReject();
  }
  catch (e) {
    return 'caught';
  }
}

调用 foo,函数返回的 Promise 等待 1 秒,而后 fulfill with "yay", or fulfill with "caught"

这个是最符合咱们预期的写法。

咱们能够把它拆分一下:

async function foo() {
  try {
    // 等待 waitAndMaybeReject() 函数的结果
    // 把 fulfilled value 赋值给 fulfilledValue:
    const fulfilledValue = await waitAndMaybeReject();
    // 若是 waitAndMaybeReject() 失败,抛出异常:
    return fulfilledValue;
  }
  catch (e) {
    return 'caught';
  }
}

阅读原文:await vs return vs return await

讨论地址:await、return 和 return await 的陷阱 #12

若是你想参与讨论,请点击这里

相关文章
相关标签/搜索