0

要件は、Q.allが正常に終了した場合に結果を返す必要があるjavascript関数内でQ.allと呼ばれるQ.js機能を使用することです。

私の目的は、wrongsizeとokaysizeという2つのプロパティを持つオブジェクトを返すことです。どちらのプロパティもjavascript配列です。

問題は、Q.allにQ.defer関数を同じ関数に含める方法がわからないことです。

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;

}
4

1 に答える 1

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
 });
于 2012-11-29T07:10:11.810 に答える