【问题标题】:return Promise vs just await this promisereturn Promise vs 只是等待这个promise
【发布时间】:2018-12-01 21:49:33
【问题描述】:

我想知道哪个代码更有意义,如果 promise 不包含值,那么返回这样的 promise 是否有任何意义:

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()

第一个选项是只在返回一些值时使用?

否则,使用第二个选项更容易,因为在函数末尾添加另一个带有“等待”的动作更容易?

async function action () {
  await asyncFunction()

  await anotherAsyncFunction()
  // easy to add another function, no need to touch "return"
  await andAnotherAsyncFunction()
}

【问题讨论】:

    标签: javascript promise async-await


    【解决方案1】:

    如果您计划让您的函数不返回任何值 (Promise<void>),我建议不要使用 return 语句。如果您希望始终返回与 anotherAsyncFunction 相同的结果,则只能使用 return anotherAsyncFunction(),无论它是什么或将来是否会改变。

    请注意,同步函数也是如此,如果您将 await 排除在外,您将做出相同的决定:return somethingsomething。 “某事”可能包含 await 并不重要,即使您是 omit the await when you choose to add the return

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 2022-07-20
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 2021-06-30
      • 2018-08-09
      • 1970-01-01
      相关资源
      最近更新 更多