在node.js中向async.parallel传递参数

Passing arguments to async.parallel in node.js

本文关键字:参数 parallel async node js 中向      更新时间:2023-09-26

我正试图创建一个最小的例子,在这里我可以完成上面描述的内容。为此,这里是我尝试的一个最小的例子,最后我希望在输出中看到

负1是-1

2加1等于3

这是我的密码。

var async = require('async');
var i, args = [1, 2];
var names = ["negative", "plusOne"];
var funcArray = [
    function negative(number, callback) {
        var neg = 0 - number;
        console.log("negative of " + number + " is " + neg);
        callback(null, neg);
    },
    function plusOne(number, callback) {
        setTimeout(function(number, callback) {
            var onemore = number + 1
            console.log("plus one of " + number + " is " + onemore);
            callback(null, onemore);
        }, 3000);
    }];
var funcCalls = {};
for (i = 0; i < 2; i++) {
    funcCalls[names[i]] = function() {
        funcArray[i].apply(this, args[i]);
    };
}
async.parallel(funcCalls, function(error, results) {
    console.log("Parallel ended with error " + error);
    console.log("Results: " + JSON.stringify(results));
});

请注意,我还将一个命名对象传递给async.parallel。传递一个数组(并完全忘记名称)对我来说也是一个答案,但我更感兴趣的是传递这样一个对象。

对实现我的目标有什么想法吗?

为什么不bind的初始值?然后你会有这样的东西:

async.parallel([
    negative.bind(null, -1),
    plusOne.bind(null, 3)
], function(err, res) {
    console.log(err, res);
});

当然,您可以使用各种参数生成列表。这只是为了给出一个简化方法的想法。

相反,您也可以使用async.apply

async.parallel(
[
  async.apply(negative, -1), //callback is automatically passed to the function
  async.apply(positive, 3)
],
(error, results) => {
console.log(error, results);
})