Javascript 回报承诺vs只是等待这个承诺
我想知道在哪种代码中更有意义,如果承诺不包含值,那么像这样返回承诺有什么意义:Javascript 回报承诺vs只是等待这个承诺,javascript,promise,async-await,Javascript,Promise,Async Await,我想知道在哪种代码中更有意义,如果承诺不包含值,那么像这样返回承诺有什么意义: async function action () { // let's say there are many such lines with await before returning await asyncFunction() // will return Promise that does not contain any value! return anotherAsyncFunction()
async function action () {
// let's say there are many such lines with await before returning
await asyncFunction()
// will return Promise that does not contain any value!
return anotherAsyncFunction()
}
// action().then(myAnotherAction)
或者更明智的做法是:
async function action () {
await asyncFunction()
await anotherAsyncFunction()
}
// const result = await action()
第一个选项是仅在返回某些值时使用
否则,使用第二个选项更容易,因为在函数末尾添加另一个带有“wait”的操作更容易
async function action () {
await asyncFunction()
await anotherAsyncFunction()
// easy to add another function, no need to touch "return"
await andAnotherAsyncFunction()
}
如果您计划函数不返回任何值(
Promise
),我建议不要使用return
语句。如果希望始终返回与另一个异步函数相同的结果,则仅使用返回另一个异步函数()
请注意,同步函数也是如此,如果您将wait
排除在图片之外,那么您将做出相同的决定:返回某个内容
而不是仅返回某个内容
。“某物”可能包含一个wait
,这并不重要,即使您需要