在async.series中调用async.series会产生不可预知的输出

使用caolan的asynchronous库node.js,我一直在试图调用一个函数,使用async.series内使用async.series另一个函数,但我仍然不能得到的function,以正确的顺序运行,详细下面:

terminal输出显示在第一个之前被调用的第二个函数,没有明显的原因:

 The "sys" module is now called "util". It should have a similar interface. Starting the second step in the series Value of b: undefined Invoking the function firstStep the value of toObtain is: [object Object] 

这里是相应的源代码:

 var im = require('imagemagick'); var async = require('async'); var toObtain; var b; async.series([ function (callback) { //It appears that this function is being invoked after the second function. //Why is this happening? firstStep(); callback(); }, function (callback) { //Why is the output of this function being displayed BEFORE the output of the function above? It's the opposite of the order in which I'm calling the functions. console.log("Starting the second step in the series"); console.log("Value of b: " + b); }]); function firstStep(){ async.series([ function (next) { // step one - call the function that sets toObtain im.identify('kittens.png', function (err, features) { if (err) throw err; console.log("Invoking the function firstStep"); toObtain = features; //console.log(toObtain); b = toObtain.height; next(); // invoke the callback provided by async }); }, function (next) { // step two - display it console.log('the value of toObtain is: %s',toObtain.toString()); }]); } 

       

网上收集的解决方案 "在async.series中调用async.series会产生不可预知的输出"

经过大约一个小时的实验,我才能正常工作。 我只是修改了firstStep函数,以便将callback函数作为参数,并在firstStep函数结束时调用callback函数。

 var im = require('imagemagick'); var async = require('async'); var toObtain = false; var b; async.series([ function (callback) { firstStep(callback); //the firstStep function takes a callback parameter and calls the callback when it finishes running. Now everything seems to be working as intended. }, function (callback) { console.log("Starting the second step in the series"); console.log("Value of b: " + b); }]); function firstStep(theCallback){ async.series([ function (next) { // step one - call the function that sets toObtain im.identify('kittens.png', function (err, features) { if (err) throw err; console.log("Invoking the function firstStep"); toObtain = features; //console.log(toObtain); b = toObtain.height; next(); // invoke the callback provided by async }); }, function (next) { // step two - display it console.log('the value of toObtain is: %s',toObtain.toString()); theCallback(); }]); }