简体   繁体   中英

NodeJS wait till all the async commands are completed

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);
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM