将 async 附加到返回 promise 的函数有什么好处? [英] What is the benefit of prepending async to a function that returns a promise?

查看:19
本文介绍了将 async 附加到返回 promise 的函数有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处添加异步有什么好处?

What is the benefit of prepending async here?

async function asyncFunc () {
   return new Promise (function (resolve, reject) {

   });
}

推荐答案

async 的唯一好处是作为一个视觉标记,该函数将(总是)返回一个 promise,而你不会甚至必须扫描return 语句的函数体.如果您有一行 async 函数,它可能对一致性很有用.

The only benefit of async is as a visual marker that the function will (always) return a promise, and you don't even have to scan the function body for the return statement. It might be useful for consistency if you have a row of async functions.

除此之外:它的收益绝对为零.这与将返回值包装在额外的 Promise.resolve() 调用中一样好.如果您的函数体仅包含带有承诺的 return 语句(new Promise 或其他函数调用),我建议不要使用 async.

Apart from that: there's absolutely zero benefit from it. It's as good as wrapping the return value in an additional Promise.resolve() call. If your function body only consists of a return statement with a promise (either a new Promise or another function call), I recommend not to use async.

通常,如果您的函数体不包含 await 表达式,您可能也不需要 async 关键字.该规则的例外情况是,当您想要确保函数总是返回一个承诺时,即使代码中出现了一个应该导致承诺拒绝的异常.

In general, if your function body does not contain an await expression, you probably don't need the async keyword either. The exception from the rule is when you want to make sure that the function always returns a promise, even if there's an exception raised in the code which should lead to a promise rejection.

这篇关于将 async 附加到返回 promise 的函数有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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