简体   繁体   English

Node.js异步模块瀑布-动态加载和执行函数

[英]Node.js async module waterfall - dynamically load and execute functions

I am attempting to dynamically load a series of anonymous functions and execute them, passing the results of the previous to the next. 我试图动态加载一系列匿名函数并执行它们,将前一个的结果传递给下一个。

Here is an example function: 这是一个示例函数:

module.exports = function (data) {
    // do something with data
    return (data);
}

When the functions are loaded (they all sit in separate files) they are returned as an object: 加载函数时(它们全部位于单独的文件中),它们作为对象返回:

{ bar: [Function], foo: [Function] }

I would like to execute these functions using async.waterfall. 我想使用async.waterfall执行这些功能。 This takes an array of functions, not an object of functions, so I convert as follows: 这需要一个函数数组,而不是函数对象,因此我将转换如下:

var arr =[];
        for( var i in self.plugins ) {
            if (self.plugins.hasOwnProperty(i)){
                arr.push(self.plugins[i]);
            }
        }

This gives: 这给出:

[ [Function], [Function] ]

How can I now execute each function using each async.waterfall passing the result of the previous function to the next? 现在如何使用每个async.waterfall执行每个功能,将前一个功能的结果传递给下一个?


SOLUTION

Thanks to the comments from @piergiaj I am now using next() in the functions. 感谢@piergiaj的评论,我现在在函数中使用next()。 The final step was to make sure that a predefined function was put first in the array that could pass the incoming data: 最后一步是确保将预定义函数放在可以传递传入数据的数组中:

var arr =[];

    arr.push(function (next) {
        next(null, incomingData);
    });

    for( var i in self.plugins ) {
        if (self.plugins.hasOwnProperty(i)){
            arr.push(self.plugins[i]);
        }
    }

    async.waterfall(arr,done);

If you want them to pass data on to the next one using async.waterfall, instead of returning at the end of each function, you need to call the next() method. 如果希望它们使用async.waterfall将数据传递给下一个,而不是在每个函数的末尾返回,则需要调用next()方法。 Additionally, you need to have next be the last parameter to each function. 此外,您需要将next作为每个函数的最后一个参数。 Example: 例:

module.exports function(data, next){
    next(null, data);
}

The first parameter to next must be null because async.waterfall treats it as an error (if you do encounter an error in one of the methods, pass it there and async.waterfall will stop execute and finish passing the error to the final method). next的第一个参数必须为null,因为async.waterfall会将其视为错误(如果您在其中一个方法中遇到错误,则将其传递给它,并且async.waterfall将停止执行并将错误传递给最终方法) 。

You can then convert it like you already to (object to array), then call it like so: 然后可以像已经将其转换为(对象到数组)一样,然后像这样调用它:

async.waterfall(arrayOfFunctions, function (err, result) {
     // err is the error pass from the methods (null if no error)
     // result is the final value passed from the last method run    
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM