节点JSasynchronous映射是同步或asynchronous调用

当我尝试使用像瀑布,MapSeries等节点jsasynchronous模块function,其中大多数本质上是asynchronous的。 但看起来像asynchronous映射不是asynchronous的。 例如,我试过这个:

var async = require('async'); console.dir('This is the begining of the program'); async.mapSeries([6,7,8,9], justAddOne, asyncMapCompleted); function justAddOne(number, callback) { callback(null, ++number); } function asyncMapCompleted(error, result) { console.log("map completed. Error: ", error, " result: ", result); } async.map([1,2,3,4,5], justAddOne, asyncMapCompleted); console.dir('This is the end of the program'); 

我得到了以下输出:

 'This is the begining of the program' map completed. Error: null result: [ 2, 3, 4, 5, 6 ] 'This is the end of the program' map completed. Error: null result: [ 7, 8, 9, 10 ] 

我们可以从输出中看到,当我们调用async.map函数时,执行线程会停止它们直到完成(我们得到输出“”这是asynchronous映射之后的程序结束)。

但是,我们在程序开始时调用了asynchronousmapSeries,它不会停止执行,而是在“结束程序”消息之后打印结果。

那么,async.map是一个同步调用? 我试图检查文件,但无法find它。

根据源代码, async.eachOf (从map调用)没有做任何asynchronous操作, async.eachOfSeries (从mapSeriesasync.setImmediate内部使用async.setImmediate

这一切都取决于你是否同时调用callback 。 你可以通过使用ensureAsync来确保它是asynchronous的:

 async.map([1,2,3,4,5], async.ensureAsync( justAddOne ), asyncMapCompleted);