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

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

问题描述

在这里预先添加异步有什么好处?

What is the benefit of prepending async here?

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

   });
}


推荐答案

<$的唯一好处c $ c> async 作为一个可视标记,该函数将(总是)返回一个promise,你甚至不必扫描函数体以获取 return 声明。如果你有一行 async函数 s,它可能对于一致性很有用。

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()调用中包装返回值一样好。如果你的函数体只包含带有promise的 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.

一般来说,如果你的函数体不包含等待表达式,您可能不需要 async 关键字。规则的例外是当你想确保函数总是返回一个promise时,即使代码中引发了一个异常会导致promise拒绝。

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天全站免登陆