Node JS Async Map是同步或异步调用

时间:2016-01-05 02:38:19

标签: node.js asynchronous

当我尝试使用诸如waterfall,mapSeries等节点js异步模块功能时,大多数都是异步的。但看起来异步映射不是异步的。例如,我试过这个:

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函数时,执行线程会停止它们直到它完成(我们得到输出“'这是程序结束'”async map之后)。

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

那么,async.map是同步调用吗?我试图检查文档但无法找到它。

2 个答案:

答案 0 :(得分:1)

根据消息来源,async.eachOf(从map调用)没有做任何会使其异步的内容,其中async.eachOfSeries(从mapSeries调用)使用{内部{1}}

答案 1 :(得分:0)

这完全取决于您是否同步拨打for i in a.shape[0]: for j in a.shape[1]: for z in a.shape[2]: a[i,j,z][b[i,j,z]] = 1 。您可以使用ensureAsync

确保它是异步的
a[b] = 1
相关问题