NodeJS 等待所有异步命令完成
NodeJS wait till all the async commands are completed
我正在使用“Q”库在 NodeJS 中进行异步调用。
但是,在其中一个用例中,我需要 defer
promise
直到所有异步调用完成。
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;
}
您可以使用Q.all
Q.all(files.map(function (map) {
return _this.readFile(map);
}));
我正在使用“Q”库在 NodeJS 中进行异步调用。
但是,在其中一个用例中,我需要 defer
promise
直到所有异步调用完成。
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;
}
您可以使用Q.all
Q.all(files.map(function (map) {
return _this.readFile(map);
}));