【问题标题】:What would be the right approach to use await instead of Promises?使用 await 而不是 Promises 的正确方法是什么?
【发布时间】:2018-06-04 17:05:18
【问题描述】:

我已经使用 Promises 很长时间了,它们始终是我用来控制程序工作流程的“东西”。示例:

Promise
  .resolve(obj)
  .then(doSomething1)
  .then(doSomething2)
  .catch(handleError)

现在,我想更改为 try-catch 样式,但我不知道究竟什么是正确的方法。

V1:

try {
  var body = await Promise
               .resolve(obj)
               .then(doSomething1)
               .then(doSomething2)
} catch (error) {
  callback(error)
}
callback(null, {
  statusCode: 200,
  body
})

V2:

try {
  var body = await Promise
               .resolve(obj)
               .then(doSomething1)
               .then(doSomething2)
               .then(body => {
                 callback(null, {
                   statusCode: 200,
                   body
                 })
               })
} catch (error) {
  callback(error)
}

什么是正确的方法?

【问题讨论】:

  • 我认为在这种情况下没有正确的方法。这取决于什么是最可维护的。
  • 有点基于意见的问题,但我更喜欢 V1。最好让callback 调用彼此靠近,而不是一个在.then 中,另一个在catch 块中。但我最喜欢的 sn-p 实际上是第一个只使用 Promise 的。
  • 我不明白您为什么要首先更改为try
  • 在任何情况下,您都不会调用回调,而是将resolve返回一个返回的promise。
  • 您的 V1 不工作。如果出现错误,callback 会被调用两次。

标签: javascript node.js asynchronous promise async-await


【解决方案1】:

您不必使用回调函数来切换到async/awaitasync 函数只是一个 Promise-returning 函数,await 是为了方便。所以相当于你原来的功能很简单:

async function fn() {
  try { 
    const obj = ...;
    const result1 = await doSomething1(obj);
    const result2 = await doSomething2(result1);
    return result2;
  } catch (err) {
    return handleError(err);
  }
}

如果你确实想要那个回调:

async function fn(callback) {
  try { 
    const obj = ...;
    const result1 = await doSomething1(obj);
    const result2 = await doSomething2(result1);
    callback(null, result2);
  } catch (err) {
    callback(err);
  }
}

【讨论】:

  • Do not forget to await doSomething2() 在您的第一个 sn-p 中调用
  • 任何返回都包含在Promise.resolve 中。返回一个 Promise 与等待所说的 Promise 然后返回结果是一样的,所以它是一个方便的捷径,只是返回最终的 Promise。
猜你喜欢
  • 2021-11-15
  • 2018-04-15
  • 2014-09-20
  • 1970-01-01
  • 2021-07-06
  • 2017-12-28
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多