gpt4 book ai didi

javascript - 为什么 Async.parallel 回调返回意外结果?

转载 作者:行者123 更新时间:2023-12-03 11:25:57 25 4
gpt4 key购买 nike

以下函数是我正在处理的稍微复杂一点的函数的抽象版本。有人可以告诉我为什么 async.parallel 的回调为 allitems 数组返回的值与返回我期望的数组的Waterfallfunction2 不同吗?

var async = require('async');

async.waterfall([


//Waterfallfunction 1
function(callback) {
var allitems = [];
async.parallel([
//Parallel 1
function(callback) {
console.log("Waterfall 1 -> parallel 1");
async.each([1, 2, 3, 4, 5, 6], function(item, callback) {
allitems.push(item * 3);
callback(null);
}, callback(null));
},
//Parallel 2
function(callback) {
console.log("Waterfall 1 -> parallel 2");
async.each([1, 2, 3], function(item, callback) {
allitems.push(item * 3 * 9);
callback(null);
}, callback(null));
},
//Parallel 3
function(callback) {
console.log("Waterfall 1 -> parallel 3");
async.each([1, 2, 3, 4, 5, 6, 7, 8, 9], function(item, callback) {
allitems.push(item * 2);
callback(null);
}, callback(null));
}

],
//Callback parallel completed
function(err, results) {
if (err) {
callback(err);
}

console.log("Waterfall 1 parallel completed");
//I expect all item to be
//[ 3, 6, 9, 12, 15, 18, 27, 54, 81, 2, 4, 6, 8, 10, 12, 14, 16, 18 ]
console.log(allitems);
// but it logs
// [ 3, 6, 9, 12, 15, 18, 27, 54, 81 ]


//pass allitems to the next function in waterfall
callback(null, allitems);
});
},
// Waterfallfunction2
//calculate items length
function(allitems, callback) {


var itemlength = allitems.length;

//pass itemlength to next function
callback(null, itemlength);
},

//Waterfallfunction3
//Log Message
function(itemlength, callback) {

console.log("The array is " + itemlength + " long");
callback(null);
}
],
//Callbackfunction on Waterfall completed
function(err, result) {
if (err) {
console.log(err);
}
console.log("operations completed!");

});

最佳答案

阅读你的回调 hell 太难了......
我尝试写同样的东西并且一切正常:)

var async = require('async');

var cascade1 = function(next) {
var all = [];
async.parallel([
function task1(next) {async.each([1, 2, 3], function(i, next){all.push(i);next();}, next) },
function task2(next) {async.each([1, 2, 3], function(i, next){all.push(2*i);next();}, next) },
function task3(next) {async.each([1, 2, 3], function(i, next){all.push(3*i);next();}, next) },
], function(){
next(null, all);
});
};

var cascade2 = function (items, next) {
console.log(items);
next(null, items.length);
}

async.waterfall([cascade1, cascade2], function(err, len){
console.log(err, len);
});

我发现了一个错误!您正在调用回调,而不是在并行调用中传递它! =)
只需将 callback(null) 更改为您想要传递回调的 callback 即可。

关于javascript - 为什么 Async.parallel 回调返回意外结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26915542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com