【问题标题】:Using async-await in promises在 Promise 中使用 async-await
【发布时间】:2021-07-08 19:27:38
【问题描述】:
.then(async (rows) => {
//some code
response = await sendEmail(email);
}

您好,如果我们引用另一个接口发送电子邮件,可以让promises中的then方法异步吗?

【问题讨论】:

  • 是的,这就像为链返回一个承诺。没关系。虽然我会检查你为什么需要混合.then。坚持一个或另一个promise api通常更容易

标签: node.js async-await promise


【解决方案1】:

虽然这可行,但 IMO 将 async/await 与承诺链混合使用是一种不好的风格。为什么不只是

 fooPromise()
  .then(rows => {
    ...
    return sendEmail(email);
  })
  .then(response => {
    ...
  })

async function foo() {
   const rows = await fooPromise();
   ...
   const response = await sendEmail(email);
   ...
}

也就是说,选择一种你更喜欢的方式并坚持下去。

【讨论】:

    【解决方案2】:

    同意@derpirscher 的回答。 async/await 语法主要是 promise 的语法糖,但它可以为易读性创造奇迹。你也可以试试:

    async function doSomething() {
    let response;
    try {
        response = await sendEmail(email);
    } catch (err) {
        console.log(err);
        return []
    }
    return response
    

    您可以找到resource about async javascript and promises here

    【讨论】:

      猜你喜欢
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-30
      • 1970-01-01
      • 2018-05-16
      • 1970-01-01
      • 2020-10-10
      • 2018-01-14
      相关资源
      最近更新 更多