【问题标题】:Ensuring an async method fires after a callback确保在回调后触发异步方法
【发布时间】:2020-10-08 13:38:48
【问题描述】:

我有一个旧的 javascript 库,我正在使用这样的回调:

async function usingOldLibrary() {
   await someAsyncFunction()
   oldLibraryFunction()
   .on('start', input => {//do something})
   .on('end', async() => {//clean up})
}

在我的'main'函数中,它都是这样调用的:

async function main() {
 await usingOldLibrary()
 await doAnotherAsyncFunction()
}
main()
  .then(() => console.log('done'))

我的问题:在main() 中,我调用了usingOldLibrary(),在.on('end') 回调触发之前,我已经调用了doAnotherAsyncFunction(),尽管我在main() 中使用了await

显然,回调的计时/混合不尊重 async/await 代码,但我不确定如何使这个旧库及其回调与它一起工作,如果我可以在某处包装承诺或确保什么doAnotherAsyncFunction 在回调完成后发生?

【问题讨论】:

  • 为什么会有开始事件?调用旧函数时任务不会启动吗?是否有可能多次触发这些开始/结束事件中的任何一个?

标签: javascript async-await callback


【解决方案1】:

异步函数默认返回Promise,你可以指定在.on('end')内部触发解析,如下所示:

async function usingOldLibrary() {
  await someAsyncFunction()

  return new Promise((resolve) => {
    oldLibraryFunction()
      .on('start', input => {//do something})
      .on('end', async() => {
         //clean up

         resolve()
      })
  })
}

【讨论】:

  • 处理程序中的async 关键字可能是不必要的
猜你喜欢
  • 1970-01-01
  • 2015-11-21
  • 2015-05-29
  • 1970-01-01
  • 2016-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多