如何使用async.waterfall与现有的回调

时间:2013-12-13 22:25:55

标签: javascript node.js asynchronous node-async

我有一组命令对象。我需要按顺序在每个数组元素上调用do命令,这是一个异步调用。如果有任何失败,我需要停止处理。

我知道如何为异步调用执行async.waterfall调用,但我无法弄清楚如何将异步调用数组传递给async.waterfall。

从语法上讲,不确定如何设置它。

这是Command对象,而read函数是我需要以瀑布方式进行的异步调用...

var ICommand = require('./command');

function FabricCommand (name) {
    this.name = name;
    this.fabric = '';
    ICommand.call(this);
}

// inherit ICommand
FabricCommand.prototype = new ICommand();

FabricCommand.prototype.read = function () {
    var URL = require('url');
    var Fabric = require('./rsp_fabrics_port_status_s');
    var ResponseVerifier = require('./rsp_mgmt_rsp_s');
    var client = require('./soap_client').getInstance();

    if (client === null) {
        throw new Error('Failed to connect to SOAP server!');
    }

    var xml = '<urn:mgmtSystemGetInterfaceStatus>' +
        '<interface xsi:type=\'xsd:string\'>' + this.name + '</interface>' +
        '</urn:mgmtSystemGetInterfaceStatus>';

    client.MgmtServer.MgmtServer.mgmtSystemGetInterfaceStatus(xml, function (err, result) {
        console.log('got the response from the backend for mgmtSystemGetInterfaceStatus');

        if (err) {
            throw new Error(err);
        }

        var rs = new ResponseVerifier(result.rsp);
        if (rs.failed()) {
            throw new Error(rs.getErrorMessage())
        }

        this.fabric = new Fabric(result.rsp.portStatus.item[0]);
    });
};

1 个答案:

答案 0 :(得分:2)

来自docs

  

运行一系列函数,每个函数都将结果传递给   数组中的下一个。但是,如果任何函数传递错误   回调,下一个函数没有执行和主   立即调用带有错误的回调。

修改

var myArray = [
    function(callback){
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback){
        callback(null, 'three');
    },
    function(arg1, callback){
        // arg1 now equals 'three'
        callback(null, 'done');
    }
];
var myCallback = function (err, result) {
   // result now equals 'done'    
};

async.waterfall(myArray, myCallback);

//If you want to add multiple Arrays into the waterfall:
var firstArray = [...],
    secondArray = [...];
async.waterfall([].concat(firstArray,secondArray),myCallback);

EDIT2:

var fabricArray = [];

for (var i=0;i<10;i++){
    var fabricCommand = new FabricCommand('Command'+i);//make 10 FabricCommands
    fabricArray.push(fabricCommand.read.bind(fabricArray));//add the read function to the Array
}

async.waterfall(fabricArray,function(){/**/});

//You also need to setup a callback argument
//And a callback(null); in your code