确保异步方法在回调后触发

Ensuring an async method fires after a callback

我有一个较旧的 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(),尽管我使用了 [=17] =] 在 main().

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

异步函数returns默认为Promise,你可以指定在.on('end')中触发的解析,如下所示:

async function usingOldLibrary() {
  await someAsyncFunction()

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

         resolve()
      })
  })
}