【问题标题】:NodeJS wait till all the async commands are completedNodeJS 等待所有异步命令完成
【发布时间】:2016-07-07 16:20:46
【问题描述】:

我正在使用“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;
}

【问题讨论】:

    标签: node.js asynchronous q deferred-execution


    【解决方案1】:

    您可以使用Q.all

    Q.all(files.map(function (map) {
        return _this.readFile(map);
    }));
    

    【讨论】:

    • 感谢您的解决方案,但我想得有点早:)
    猜你喜欢
    • 2018-07-17
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 2016-01-29
    • 2016-03-16
    • 1970-01-01
    • 2020-10-04
    • 2011-10-04
    相关资源
    最近更新 更多