【问题标题】:async await in node callback节点回调中的异步等待
【发布时间】:2021-03-30 16:29:20
【问题描述】:

我有一个使用 3rd 方包的服务。

exports.FOO = (options, cb) => {
  const outputPath = 'bar'
  const storePDF = async (data) => {}
  const sendBack = (outputPath, cb) => {
    fs.readFile(outputPath, encoding, async (err, data) => {
      if (err) {
       return cb(err)
      }
      if (options.source) {
       await store(data)
      }
      cb(null, data);
    })
  }
  ThirdParty.run(err => {
     if (err) {
       return cb(err)
     };
     // read the file and send it back
     sendBack(outputPath, cb)
  })
}

我想升级这个包,但它有一些重大变化,新的用法如下:

await ThirdParty.setup()
await ThirdParty.run()

我真的很想保留回调,因为这个服务在整个应用程序中都是这样使用的。我试图让 FOO async 并在 await ThirdParty.run() 之后调用 sendBack,但我得到了。

node_modules/async/dist/async.js:966

if (fn === null) throw new Error("Callback is already called.");

错误:已调用回调。

exports.FOO = async (options, cb) => {
  const outputPath = 'bar'
  const storePDF = async (data) => {}
  const sendBack = (outputPath, cb) => {
    fs.readFile(outputPath, encoding, async (err, data) => {
      if (err) {
       return cb(err)
      }
      if (options.source) {
       await store(data)
      }
      cb(null, data);
    })
  }
  await ThirdParty.setup()
  await ThirdParty.run()
  sendBack(outputPath, cb)
}

【问题讨论】:

    标签: node.js async-await


    【解决方案1】:

    将调用更改为等待。然后像以前一样调用您的回调。如果调用失败,则在catch 块中处理。

    exports.FOO = async (options, cb) => {
      //...
      try {
        await ThirdParty.run();
        // read the file and send it back
        sendBack(outputPath, cb)
      } catch (err)
         return cb(err);
      }
    }
    

    【讨论】:

    • 谢谢,但是——正如我所写的——这正是我尝试过的。
    【解决方案2】:
        exports.FOO = async (options, cb) => {
      const outputPath = 'bar'
      const storePDF = async (data) => {}
      const sendBack = (outputPath, cb) => {
        fs.readFile(outputPath, encoding, async (err, data) => {
          if (err) {
           return cb(err)
          }
          if (options.source) {
           await store(data)
          }
          cb(null, data);
        })
      }
      await ThirdParty.setup()
      await ThirdParty.run()
      sendBack(outputPath, cb) //Why are you calling sendBack here shouldn't be return without calling the function like recursion?
    }
    

    【讨论】:

    • 如果你看一下原始代码,你可以看到,ThirdParty 生成文件,完成后,sendBack 读取它,并在回调中发送回。
    • 如果你想返回读取的数据,你可以简单地返回数据而不是 sendBack(..)
    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 2016-12-26
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 2018-12-30
    相关资源
    最近更新 更多