Q.allSettled没有返回promise结果

时间:2016-03-29 15:38:21

标签: javascript promise q

我试图在Q.allSettled完成后解决延期的承诺。但是,.then的{​​{1}}永远不会执行,并且永远不会返回promise数组结果。没有异常被抛出我只是永远不会进入allSettled块。正如您从下面的代码中看到的那样,我在一个.then块内部迭代一些文件上传元素,然后根据这些返回执行文件上传和一些保存。

.then

1 个答案:

答案 0 :(得分:0)

在接受@Bergi的建议后,我重构了一堆使用deferred antipattern的代码。我最终将我的代码包装在Q.fcall块中以返回promise并将Q.allSettled更改为Q.all。以下是我的工作代码的最终状态。

注意:有Durandal特定功能的函数调用以及我省略的其他功能。

return Q.fcall(function () {
    try {

        var fileUploadPromises = [];
        var $fileUploads = $(fileUploadClass);
        var fileNamesNeeded = 0;

        $fileUploads.each(function (index, item) {
            if (item.files.length > 0)
                fileNamesNeeded++;
        });

        return datacontext.getFileNameGuid(fileNamesNeeded).then(function (data) {
            _.each($fileUploads, function (item) {
                if (item.files.length > 0) {
                    // Init upload file promise                                
                    var promise = uploadFile(item, data[remainingFilesToUpload])
                        .then(function () {
                            return datacontext.saveItem(atom)
                                .then(function (data) {
                                    return getItemSuccess(data, false);
                                });
                        }).catch(function (data) {                                        
                            logger.logError('An error occurred while updating your Item. Please try again.', data, 'Error', true);
                            app.trigger(config.publishedMessageNames.AtomFileUploaded, "");
                        });

                    fileUploadPromises.push(promise);

                    remainingFilesToUpload++;
                }
            });

            // Either execute promises or bail
            if (fileUploadPromises.length > 0) {                            
                return Q.all(fileUploadPromises)
                .then(function (results) {                                
                    return datacontext.scheduleBatchTask(filesToUpload(), item.DocumentId()).then(function () {
                        app.trigger(config.publishedMessageNames.FileUploaded, data);
                    });
                }).done();
            } else {
                app.trigger(config.publishedMessageNames.FileUploaded, "");
            }
        });                   
    } catch (e) {
        return new Error(e);
    }
});