[英]Using Future to return after a series of async calls
I am writing a JavaScript (node.js) function that makes several exec() calls (asynchronously) and I need to use Future to return after all of them are completed. 我正在编写一个JavaScript(node.js)函数,该函数(异步)进行多个exec()调用,并且在所有这些操作完成后,我需要使用Future返回。
What I have is: 我所拥有的是:
run: function(command, callback) {
for (var i = 0; i < testCases.length; i++) {
var child = exec(command, options, function(error, stdout, stderr) {
// calculate `answer`
if (answer == "wrong") callback(answer);
});
}
},
So, if answer
is "wrong", then I can easily call the callback and that's it. 因此,如果answer
是“错误的”,那么我可以轻松地调用回调,仅此而已。 However, if all the answers aren't "wrong" (in other words, if all the exec
have answer=="correct"
) then I have no idea of how to return such value. 但是,如果不是所有的答案都是“错误的”(换句话说,如果所有的exec
都具有answer=="correct"
),那么我不知道如何返回这样的值。
I know I can use Future
(from npm
) for this. 我知道我可以为此使用Future
(来自npm
)。 However, I can't really see how to use it in this case (where I don't have just 1 async call, but multiple async calls). 但是,在这种情况下(我不仅只有1个异步调用,而没有多个异步调用),我真的看不到如何使用它。
async.times(testCases.length, function(n, next){
var child = exec(command, options, function(error, stdout, stderr) {
// calculate `answer`
var data = {answer : answer};
if (answer == "wrong") {
next({err: answer}, data);
}
else {
next(null, data);
}
});
}, callback(err, data) {
// you can also check for err
// we now have an array of data[testCases.length]
});
One way to do it would be to check for the number of commands completed - 一种方法是检查已完成的命令数量-
var totalCompleted = 0;
var done = false;
for (var i = 0; i < testCases.length; i++) {
var child = exec(command, options, function(error, stdout, stderr) {
// calculate `answer`
totalCompleted++;
if (answer == "wrong" && !done) {
done = true;
return callback(answer);
}
if(totalCompleted === testCases.length && !done) {
callback('right');
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.