【问题标题】:nodejs loop async.parallel callbacknodejs 循环 async.parallel 回调
【发布时间】:2017-05-03 09:50:22
【问题描述】:

我正在测试由 async.parallel 函数调用的回调:如果回调使用参数或不使用参数,执行流程似乎有所不同。

var async = require("async");

function makeTestFunction(i) {
	return function(callback) {
		console.log('test Function: '+i);
		return callback();
	};
}

function test(callback) {
	var endFunctions = function(i) {
		console.log('ending: ' + i);
		return callback();
	};
	var testFunctions = [];
	for (var i=0; i < 3; i++) {
		console.log('loop: '+i);
		testFunctions.push(makeTestFunction(i));
	}
	return async.parallel(testFunctions, endFunctions );
}

test( function() {
	console.log('--------------- end test 1');
});
// loop: 0
// loop: 1
// loop: 2
// test Function: 0
// test Function: 1
// test Function: 2
// ending: null
// --------------- end test 1

结果如我所料:在所有函数完成后调用“endFunctions”回调。

现在我希望匿名函数回调返回一个值:

var async = require("async");

function makeTestFunction(i) {
	return function(callback) {
		console.log('test Function: '+i);
		return callback(i);
	};
}

function test(callback) {
	var endFunctions = function(i) {
		console.log('ending: ' + i);
		return callback();
	};
	var testFunctions = [];
	for (var i=0; i < 3; i++) {
		console.log('loop: '+i);
		testFunctions.push(makeTestFunction(i));
	}
	return async.parallel(testFunctions, endFunctions );
}

test( function() {
	console.log('--------------- end test 2');
});
// loop: 0
// loop: 1
// loop: 2
// test Function: 0
// test Function: 1
// ending: 1
// --------------- end test 2
// test Function: 2

阅读async.parralel manual,我期待:

  1. 在所有匿名函数终止后调用一次回调“endFunctions”
  2. 回调“endFunctions”接收匿名函数返回的所有值的数组。

请问,有人能解释一下发生了什么,出了什么问题吗?

【问题讨论】:

  • 我不确定这个问题是否重复。这并不明显。请仔细阅读
  • 问题是关于 async.parallel (nodejs)

标签: javascript node.js callback async.js


【解决方案1】:

问题是回调签名。 对于 async.parallel,回调必须有两个参数(err,results)。

以下代码给出了正确的结果:

var async = require("async");

function makeTestFunction(i) {
	console.log('make function: '+i);
	return function(callback) {
		console.log('test Function: '+i);
		return callback(null, i);
	};
}

function test(callback) {
	var endFunctions = function(err, result) {
		console.log('ending: ' + result);
		return callback();
	};
	var testFunctions = [];
	for (var i=0; i < 3; i++) {
		(function (k) {
			testFunctions.push(makeTestFunction(k));
		})(i);
	}
	return async.parallel(testFunctions, endFunctions );
}

test( function() {
	console.log('--------------- end test 2');
});
// make function: 0
// make function: 1
// make function: 2
// test Function: 0
// test Function: 1
// test Function: 2
// ending: 0,1,2
// --------------- end test 2

【讨论】:

    猜你喜欢
    • 2016-05-28
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2021-05-28
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多