【问题标题】:Need a way or a tool to await a code block in node需要一种方法或工具来等待节点中的代码块
【发布时间】:2017-05-17 13:04:04
【问题描述】:

ES2017 async/await 功能很棒。它减少了编写递归回调的痛苦。但是,我有时会看到像 unhandled promise rejection 这样的 nodejs 运行时警告。原因是我忘记在 async 代码块中的每个位置都放置 await

function action1Async() {
  return new Promise((resolve, reject) => {
    resolve('good name async function')
  })
}
async function action2() {
  return new Promise((resolve, reject) => {
    reject('bad name async function')
  })
}

async function main() {
  const r1 = await action1Async()
  const r2 = action2() // The name is bad, I dont realize it is an async function. Actually throw an exception
  return r1 + r2
}

从代码示例中可以看出,除非我在每个函数调用中都加上await,否则很容易让代码出错。我相信 ES 起草社区有理由发明 await 来控制 async 块内的行为。

我编写正确的代码没有问题。但我认为在我打算同步运行的代码块中编写这么多await 会太全面。是否可以像协程一样自动解析代码块内的所有承诺?使用一些静态工具或神奇的 JS 库?

提前致谢

【问题讨论】:

    标签: node.js async-await coroutine


    【解决方案1】:

    如果您可以将结果作为值数组处理,Promise.all 函数将可以正常工作。

    async function main() {
      const r1 = await action1Async()
      const r2 = action2() // The name is bad, I dont realize it is an async function. Actually throw an exception
      return Promise.all([r1, r2]).then(function (res) {
          return res[0] + res[1];
      })
    }
    
    main()
    .then(console.log)
    .catch(console.log);
    

    【讨论】:

      猜你喜欢
      • 2018-03-26
      • 2021-01-10
      • 1970-01-01
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-12-12
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多