0

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

我知道如何为个人异步调用执行 async.waterfall 调用,但我不知道如何将异步调用数组传递给 async.waterfall。

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

这是命令对象,读取函数是我需要以瀑布方式执行的异步调用...

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]);
    });
};
4

1 回答 1

2

文档

依次运行一组函数,每个函数将其结果传递给数组中的下一个函数。但是,如果任何函数将错误传递给回调,则不会执行下一个函数,并且会立即调用带有错误的主回调。

编辑

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);

编辑2:

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
于 2013-12-13T22:32:48.933 回答