async.waterfall和变量范围

时间:2015-12-15 10:33:16

标签: javascript node.js scope async.js

我正在运行这个简单的代码作为我需要为我的项目制作的函数的测试:

var async = require('async');

test_function = function(a,b,callback){
    console.log(a,b);
    callback(null,a+b)  
};

var array = [12,7,3,4,2];
var waterfall_array = [];

waterfall_array.push(function(callback_waterfall){
    test_function(array[0],3,callback_waterfall)
});

for(var i=1; i<array.length; i++){
    waterfall_array.push(function(arg,callback_waterfall){
        var array_bis = array ;
        console.log(array_bis,array_bis[1]);
        test_function(array_bis[i],arg,callback_waterfall);
    });
}

async.waterfall(waterfall_array,function(error,result){
    if(error){
        console.log('error');
    }
    else{
        console.log(result);
    }
});

以下是我在控制台中获得的内容:

12 3
[ 12, 7, 3, 4, 2 ] 7
undefined 15
[ 12, 7, 3, 4, 2 ] 7
undefined NaN
[ 12, 7, 3, 4, 2 ] 7
undefined NaN
[ 12, 7, 3, 4, 2 ] 7
undefined NaN
NaN

为什么我不能在我的瀑布函数中将array_bis [i]作为参数?

看看另一个有趣的答案,我试过这个:

var async = require('async');

test_function = function(a,b,callback){
    console.log(a,b);
    callback(null,a+b)  
};

var array = [12,7,3,4,2];
var waterfall_array = [];

waterfall_array.push(function(callback_waterfall){
    test_function(array[0],3,callback_waterfall)
});

functioncreate = function(array_index){
    return function(arg_waterfall,callback){
        test_function(array[array_index],arg_waterfall,callback);
    };
}

var function_array = [];
for (var j=1;j<array.length;j++){
    function_array.push(functioncreate(j));
}

console.log(function_array);

for(var i=1; i<array.length; i++){
    waterfall_array.push(function(arg,callback_waterfall){
        function_array[i](arg,callback_waterfall);
    });
}

async.waterfall(waterfall_array,function(error,result){
    if(error){
        console.log('error');
    }
    else{
        console.log(result);
    }
});

但是我返回了错误:TypeError:function_array [i]不是函数

我不明白,因为function_array [i]应该是functioncreate返回的函数。

你对此有什么建议吗?

谢谢:)

好的,这是正确的代码:

var async = require('async');

test_function = function(a,b,callback){
    console.log(a,b);
    callback(null,a+b)  
};

var array = [12,7,3,4,2];
var waterfall_array = [];

waterfall_array.push(function(callback_waterfall){
    test_function(array[0],3,callback_waterfall)
});

functioncreate = function(array_index,arg_waterfall,callback){
    return (function(arg_waterfall,callback){
        test_function(array[array_index],arg_waterfall,callback);
    });
}

var function_array = [];
for (var j=1;j<array.length;j++){
    waterfall_array.push(functioncreate(j));
}

console.log(function_array);

async.waterfall(waterfall_array,function(error,result){
    if(error){
        console.log('error');
    }
    else{
        console.log(result);
    }
});

谢谢!

0 个答案:

没有答案