混合asynchronous操作(callback和承诺)完成后如何执行任务?

我在写一些nodejs应用程序。 我的应用程序有一些npm模块的依赖。

在一个任务中,涉及两个asynchronous操作,两个asynchronous操作是以callback和承诺的forms。 下面我把一些示例代码:

// the task which should be performed after async operation var myTask = function(){ // do something } // first async operation in the form of callback cbapi(myTask) // second async operation in the form of promise promiseapi() .then(myTask) 

在上例中,当第一次asynchronous和第二次asynchronous操作完成时, myTask将执行两次。 但是,我想要的是只有在两个asynchronous操作完成后才执行一次。

有没有办法做到这一点?

围绕您的callback函数调用构build一个新的Promise,并在两个调用上使用Promise.all

 Promise.all([new Promise(resolve => cbapi(resolve)), promiseapi()]) .then(myTask) .catch(e => console.error(e)); 

myTask将被包含两个调用结果的数组调用。

正如@esaukuhabuild议的,你应该promisify你的callbackAPI,然后使用它们。

 new Promise((resolve, reject) => cbapi((err, result) => { if (err) reject(err); else resolve(result); }) ) .then(myTask) // ... chain 

我有一个小npm模块只是为了这个。

 import fromCallback from 'promise-cb/from'; fromCallback(cb => cbapi(cb)) .then(myTask) // ... chain