更新2
完整代码列表
var request = require('request');
var cache = require('memory-cache');
var async = require('async');
var server = '172.16.221.190'
var user = 'admin'
var password ='Passw0rd'
var dn ='\\VE\\Policy\\Objects'
var jsonpayload = {"Username": user, "Password": password}
async.waterfall([
//Get the API Key
function(callback){
request.post({uri: 'http://' + server +'/sdk/authorize/',
json: jsonpayload,
headers: {'content_type': 'application/json'}
}, function (e, r, body) {
callback(null, body.APIKey);
})
},
//List the credential objects
function(apikey, callback){
var jsonpayload2 = {"ObjectDN": dn, "Recursive": true}
request.post({uri: 'http://' + server +'/sdk/Config/enumerate?apikey=' + apikey,
json: jsonpayload2,
headers: {'content_type': 'application/json'}
}, function (e, r, body) {
var dns = [];
for (var i = 0; i < body.Objects.length; i++) {
dns.push({'name': body.Objects[i].Name, 'dn': body.Objects[i].DN})
}
callback(null, dns, apikey);
})
},
function(dns, apikey, callback){
// console.log(dns)
var cb = [];
for (var i = 0; i < dns.length; i++) {
//Retrieve the credential
var jsonpayload3 = {"CredentialPath": dns[i].dn, "Pattern": null, "Recursive": false}
console.log(dns[i].dn)
request.post({uri: 'http://' + server +'/sdk/credentials/retrieve?apikey=' + apikey,
json: jsonpayload3,
headers: {'content_type': 'application/json'}
}, function (e, r, body) {
// console.log(body)
cb.push({'cl': body.Classname})
callback(null, cb, apikey);
console.log(cb)
});
}
}
], function (err, result) {
// console.log(result)
// result now equals 'done'
}); 更新:
我正在构建一个小型应用程序,它需要对一个外部API进行多个HTTP调用,并将结果合并到一个对象或数组中。例如:
下面的原始问题概述了我到目前为止尝试过的!
原始问题:
async.waterfall方法是否支持多个回调?
也就是说,迭代从链中的前一个项传递的数组,然后调用多个http请求,每个请求都有自己的回调。
例如,
sync.waterfall([
function(dns, key, callback){
var cb = [];
for (var i = 0; i < dns.length; i++) {
//Retrieve the credential
var jsonpayload3 = {"Cred": dns[i].DN, "Pattern": null, "Recursive": false}
console.log(dns[i].DN)
request.post({uri: 'http://' + vedserver +'/api/cred/retrieve?apikey=' + key,
json: jsonpayload3,
headers: {'content_type': 'application/json'}
}, function (e, r, body) {
console.log(body)
cb.push({'cl': body.Classname})
callback(null, cb, key);
});
}
}发布于 2013-06-27 09:08:09
希望我能正确理解你的问题。在我看来,您想要为dns中的每一项调用api,并且需要知道它们何时完成。当您有一个使用前面函数的结果的函数链时,通常使用async.waterfall。在您的例子中,我只能看到您需要在一个回调中使用所有api调用的结果。而且,由于您还希望创建一个新数组,所以我将使用async.map。
更新:
如果您想在async.waterfall中创建一个循环,异步/map是首选的武器。下面的代码将在每个dns被调用时调用瀑布回调。
async.waterfall([
// ...,
function(dns, apikey, callback){
async.map(dns, function (item, next) {
var jsonpayload3 = {
Cred: dns[i].DN,
Pattern: null,
Recursive: false
};
request.post({
uri: 'http://' + vedserver +'/api/cred/retrieve?apikey=' + key,
json: jsonpayload3,
headers: {'content_type': 'application/json'}
}, function (e, r, body) {
next(e, { cl: body.Classname });
});
},
callback);
}],
function (err, result) {
// result now looks like [{ cl: <body.Classname> }]
});https://stackoverflow.com/questions/17337994
复制相似问题