`return await promise` 和 `return promise` 之间的区别 [英] Difference between `return await promise` and `return promise`

查看:34
本文介绍了`return await promise` 和 `return promise` 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于下面的代码示例,行为上是否有任何差异,如果有,这些差异是什么?

Given the code samples below, is there any difference in behavior, and, if so, what are those differences?

返回等待承诺

async function delay1Second() {
  return (await delay(1000));
}

返回承诺

async function delay1Second() {
  return delay(1000);
}

据我所知,第一个将在异步函数中进行错误处理,并且错误会从异步函数的 Promise 中冒泡出来.但是,第二个需要少一个刻度.这是正确的吗?

As I understand it, the first would have error-handling within the async function, and errors would bubble out of the async function's Promise. However, the second would require one less tick. Is this correct?

这个代码片段只是一个返回 Promise 以供参考的常用函数.

This snippet is just a common function to return a Promise for reference.

function delay(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

推荐答案

大多数时候,returnreturn await 之间没有明显的区别.delay1Second 的两个版本都具有完全相同的可观察行为(但取决于实现,return await 版本可能会使用稍微更多的内存,因为中间 Promise> 可能会创建对象).

Most of the time, there is no observable difference between return and return await. Both versions of delay1Second have the exact same observable behavior (but depending on the implementation, the return await version might use slightly more memory because an intermediate Promise object might be created).

然而,正如@PitaJ 指出的,有一种情况存在差异:如果 returnreturn await 嵌套在 try-catch 块.考虑这个例子

However, as @PitaJ pointed out, there is one case where there is a difference: if the return or return await is nested in a try-catch block. Consider this example

async function rejectionWithReturnAwait () {
  try {
    return await Promise.reject(new Error())
  } catch (e) {
    return 'Saved!'
  }
}

async function rejectionWithReturn () {
  try {
    return Promise.reject(new Error())
  } catch (e) {
    return 'Saved!'
  }
}

在第一个版本中,async函数在返回结果之前等待被拒绝的promise,这导致拒绝变成异常并且到达catch子句;因此,该函数将返回一个解析为字符串已保存!"的承诺.

In the first version, the async function awaits the rejected promise before returning its result, which causes the rejection to be turned into an exception and the catch clause to be reached; the function will thus return a promise resolving to the string "Saved!".

然而,该函数的第二个版本确实直接返回被拒绝的承诺而无需在异步函数中等待它,这意味着 catch 的情况是 没有被调用,而调用者却得到了拒绝.

The second version of the function, however, does return the rejected promise directly without awaiting it within the async function, which means that the catch case is not called and the caller gets the rejection instead.

这篇关于`return await promise` 和 `return promise` 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆