4

node.js用のcaolanの非同期ライブラリを使用してasync.series、async.seriesを使用する別の関数内で使用する関数を呼び出そうとしましたが、以下に詳述するように、関数を正しい順序で実行することはできません:

ターミナル出力は、明らかな理由もなく、最初の関数の前に 2 番目の関数が呼び出されていることを示しています。

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

1 に答える 1

6

約 1 時間の実験の後、正常に動作するようになりました。コールバック関数をパラメーターとして取り、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();
    }]);
}
于 2012-09-23T17:30:20.857 に答える