简体   繁体   English

为什么我的诺言没有得到解决?

[英]Why isn't my promise getting resolved?

I have two functions - A helper function for downloading files which is as follows 我有两个功能-一个下载文件的辅助功能,如下

var downloadHelper = function(url, saveDir) {
    var deferred = Q.defer();

    setTimeout(function() {
        deferred.resolve("success");    
    }, 2000);


    return deferred.promise;
}

Now I have a list of files to be downloaded in parallel. 现在,我有了要并行下载的文件列表。 I have the logic for that function as follows: 我对该函数的逻辑如下:

var downloadAll = function() {
    var fileDownloadList = []
    for(var key in config.files) {

        var deferred = Q.defer();
        var saveLocation = __base + config.localDir
        downloadHelper(
            config.files[key], 
            saveLocation
        ).then(function() {
            deferred.resolve("downloaded: " + fileUrl);
        }).catch(function(err) {
            deferred.reject(err);
        });

        fileDownloadList.push(deferred.promise);
    }

    Q.all(fileDownloadList).done(function() {
        console.log("All downloaded");
    },function(err) {
        console.log(err);
    });

    setTimeout(function() {
        console.log(fileDownloadList);
    }, 10000);
}

The done is never getting called! 完成永远不会被召唤!

For debugging purposes, I added a setTimeout that will be called after 10 seconds and what I see is that out of 2 files, the second promise is resolved and the first one is still in pending state. 出于调试目的,我添加了一个setTimeout,它将在10秒后调用,并且我看到的是2个文件中的第2个承诺已解决,第一个仍处于待处理状态。

Any ideas? 有任何想法吗?

Thanks in advance 提前致谢

One way to make your code work 一种使代码正常工作的方法

for(var key in config.files) {
    (function() {
        var deferred = Q.defer();
        var saveLocation = __base + config.localDir
        downloadHelper(
            config.files[key], 
            saveLocation
        ).then(function() {
            deferred.resolve("downloaded: " + fileUrl);
        }).catch(function(err) {
           deferred.reject(err);
        });
        fileDownloadList.push(deferred.promise);
    }());
}

But since downloadhelper returns a promise, no need to create yet another one 但是由于downloadhelper返回了一个承诺,因此无需创建另一个

for (var key in config.files) {
    var saveLocation = __base + config.localDir
    fileDownloadList.push(downloadHelper(
        config.files[key],
        saveLocation
    ).then(function () {
        return("downloaded: " + fileUrl);
    }));
} 

You'll see I removed 你会看到我被删除

.catch(function(err) {
    deferred.reject(err);
})

That's redundant, it's the same as not having the catch at all 这是多余的,就像根本没有抓住一样

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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