如何在我使用Q.all的同一个函数中使用defer和deferred.resolve?

时间:2012-11-29 06:44:45

标签: javascript asynchronous callback

要求是我在javascript函数中使用了名为Q.all的Q.js功能,如果Q.all成功完成,则需要返回结果。

我的目标是返回一个名为wrongsize和okaysize的属性的对象。 这两个属性都是javascript数组。

问题是我不知道如何将Q.defer函数与Q.all包含在同一个函数中。

function filterNonConformingPageSize(files) {

    var addToWhichGlobalVariable = "pageSizesOfNewFiles";

    promises = [];
    for (var i=0; i<files.length; i++) {
        promises.push(
            getSizeSettingsFromPage(files[i], addToWhichGlobalVariable, calculateRatio)
        );
    }

    // *** sort out the files after all promises have been resolved
    var resultObj = Q.all(promises).then(function() {
        var test = new Object();
        var filesWithOkaySize = new Array();
        var filesWithWrongSize = new Array();   

        for (var i=0; i<files.length; i++) {
            if (pageSizesOfNewFiles[i].size == majorityPageSize) {
                filesWithOkaySize.push(files[i]);
            } else {
                filesWithWrongSize.push(files[i].name);
            }
        }
        test['wrongsize'] = filesWithWrongSize;
        test['okaysize'] = filesWithOkaySize;

        return test;
    });

    return resultObj;

}

1 个答案:

答案 0 :(得分:0)

注意@TODO部分。

    /** iteratively calculate pagesize of the new incoming files **/
function filterNonConformingPageSize(files) {
    // @TODO Create a Deferred
    var deferred = Q.defer();

    var addToWhichGlobalVariable = "pageSizesOfNewFiles";

    promises = [];
    for (var i=0; i<files.length; i++) {
        promises.push(
            getSizeSettingsFromPage(files[i], addToWhichGlobalVariable, calculateRatio)
        );
    }


    // *** sort out the files after all promises have been resolved
    Q.all(promises).then(function() {
        var test = new Object();    
        var filesWithOkaySize = new Array();
        var filesWithWrongSize = new Array();   

        for (var i=0; i<files.length; i++) {
            var filename = files[i].name;
            var newFileSize = pageSizesOfNewFiles.getByKey(filename);
            if (newFileSize.size == majorityPageSize) {
                console.log(filename + "is right size");
                console.log(newFileSize.size);
                filesWithOkaySize.push(files[i]);
            } else {
                console.log(filename + "is wrong size");
                filesWithWrongSize.push(files[i]);
            }
        }
        test['wrongsize'] = filesWithWrongSize;
        test['okaysize'] = filesWithOkaySize;
    // @TODO add the resolve        
        deferred.resolve(test); 
    });
    // @TODO return the promise part. 
    return deferred.promise;

}

当你调用这个函数时,就像这样做

 filterNonConformingPageSize(filterDupeNameResult['okaynames']).then(function(result){
 // result will be the expected result
     // at the end of running filterNonConformingPageSize
 });