只有在执行了其他asynchronous函数后才调用函数

我只想在函数f1和f2完成后调用函数cb(注意f1和f2是asynchronous的,并且可能随时调用它们)。

我试图实现这样的东西,但它似乎不是在node.js上这样做的最好方法。

var l1 = false; var l2 = false; // function to be called after f1 and f2 have ended function cb(err, res) { if (err) { console.log(err); } else { console.log('result = ' + res); } } // f1 and f2 are practically identicals... function f1(callback) { console.log('f1 called'); l1 = true; if (l2) { console.log('f1 calling cb'); callback(null, 'one'); } else { console.log('f2 wasn\'t called yet'); } } function f2(callback) { console.log('f2 called'); l2 = true; if (l1) { console.log('f2 calling cb'); callback(null, 'two'); } else { console.log('f1 wasn\'t called yet'); } } setTimeout(function() { f1(cb); // will call cb }, 3000); setTimeout(function() { f2(cb); // won't call cb }, 1000); // It will print: // f2 called // f1 wasn't called yet // f1 called // f1 calling cb // result = one 

 var async = require('async'); console.log('before invocation'); async.parallel([ function f1(cb) { console.log('f1 invoked'); setTimeout(function () { console.log('f1 calling back'); cb(null, 'one'); }, 3000); }, function f2(cb) { console.log('f2 invoked'); setTimeout(function () { console.log('f2 calling back'); cb(null, 'two'); }, 1000); } ], function callback(err, results) { console.log('callback invoked'); if (err) { console.log(err); } else { console.log('results: ', results); } }); console.log('after invocation'); setTimeout(function () { console.log('2 seconds later...'); }, 2000); 

输出:

 before invocation f1 invoked f2 invoked after invocation f2 calling back 2 seconds later... f1 calling back callback invoked results: [ 'one', 'two' ] 

不好意思,我没有完全复制你的情况,但是我承认,你所拥有的只是一个模型。

唯一的区别是最终的callback包含了来自并行执行的每个函数的结果的数组, setTimeout()在每个函数中被调用。

请注意,返回的数组是['one', 'two'] ,因为这是传递给async.parallel()的函数的顺序。 提供给每个函数的cb参数是由async生成的,它会自动为您执行error handling和其他后台处理,类似于您如何使用两个标记,但更有组织和有效。