I am using 'Q' library to make async calls in NodeJS.
However in one of the use cases, I need to defer
the promise
till all the async calls are completed.
public someFunction(files: string[]) : Q.Promise<string> {
var needSomeInfo;
var defer = Q.defer;
for (var i = 0; i < files.length; i++) {
_this.readFile(files[i]).then(function(res) {
needSomeInfo += res.Info;
j++;
if (j == files.length) {
defer.resolve(needSomeInfo);
}
}).fail(function(err) {
j++;
if (j == resultFiles.length) {
defer.resolve(needSomeInfo);
}
//this is kinda stupid. I need to wait till all file calls are done because of consolidated info I need from them
});
}
return defer.promise;
}
You can use Q.all
Q.all(files.map(function (map) {
return _this.readFile(map);
}));