Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

javascript - What is the benefit of prepending async to a function that returns a promise?

What is the benefit of prepending async here?

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

   });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...