我想在我的服务中使用async.series([]),然后将结果返回给Controller。但是,似乎async.series的可选回调函数不会等到任务完成后再返回到控制器。
/* In Services */
getFunction: function(userInput, callback) {
var results = {};
async.series([
//1: This function get a list JSON dataset of id and other attributes
function(callback) {
//Call a function to call API by using the userInput, return function(error, JSONdataset1)
//If error, return callback(error)
//Else results = JSON.parse(dataset1);
callback(null, JSON.stringify(results));
},
//2: This function get a JSON object by input the id result from above function
//I am not sure I should use for loop here as well, can someone advise me please!
function(callback) {
for(var result in results) {
//Call another function to call API by using the id in the returned results, return function(error, JSONdataset2)
//If error, return callback(error)
//Else
var aName = JSON.parse(JSONdataset2);
results[result].name = JSON.parse(JSON.stringify(aName.attribute));
}
callback(null, JSON.stringify(results));
}
],
//res = [JSON.stringify(results), JSON.stringify(results)] and result should return to Controller
//The problem is the callback doesn't wait above functions finish before return.
function(error, res) {
if(error) { return callback(error, null); }
else { return callback(null, res); }
});
}
答案 0 :(得分:0)
在类似的情况下,我会使用async.each()函数,例如
async.each(results, function(result){
var aName = JSON.parse(JSONdataset2);
results[result].name = JSON.parse(JSON.stringify(aName.attribute));
callback();
}, function(err){
if(err) callback(err,null);
else callback(null, JSON.stringify(results));
})
这将确保在调用属于您的系列函数的回调之前迭代每个结果。
答案 1 :(得分:0)
Instead of the code I posted earlier, I used async.waterfall.