2012-09-23 82 views
4

對於node.js使用caolan的異步庫,我一直試圖調用一個函數,該函數在使用async.series的另一個函數中使用async.series,但我仍然無法得到的功能以正確的順序運行,如下面詳述:在async.series中調用async.series會產生不可預知的輸出

終端輸出顯示之前所述第一被調用第二函數,對於沒有明顯的原因:

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()); 
    }]); 
} 

回答

6

經過大約一小時的實驗後,我才得以正常工作。我只是修改firstStep函數,以便它將回調函數作爲參數,並在firstStep函數結束時調用回調函數。

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(); 
    }]); 
}