Determining the resolution of a variable number of asynchronous process triggered in loop using jQuery deferred, javascript

StackOverflow https://stackoverflow.com/questions/20713852

سؤال

I'm having some confusion about how to apply the jQuery $.deferred object for a loop of asynchronous process when the loop is of variable length. Below is my current attempt. Because the process in the loop are asynchronous the loop will complete and the deferred object in main will resolve before all the asynchronous process triggered in the loop have resolved. On the other hand I will be getting a variable number of resolutions triggered from the deferred object inside the asynchronous process as each one finishes, leaving quite a bit of accounting to determine when they have all completed.

function asyncProcess(someVariable) {
    var dfd = $.Deferred();
    //Some Code
    dfd.resolve();
    return dfd.promise();
}


function main() {
    var dfd = $.Deferred();
    for (i = 0; i < variableInteger; i++) {
        asyncProcess(someVariable);
        dfd.resolve();
    }
    return dfd.promise();
}

Does anyone know how this situation is typically handled?

هل كانت مفيدة؟

المحلول

Use $.when() to create a new promise which will be resolved when all the promises are resolved or any one is rejected.

function asyncProcess(someVariable) {
    var dfd = $.Deferred();
    //Some Code
    dfd.resolve();
    return dfd.promise();
}


function main() {
    var prmis = [];
    for (i = 0; i < variableInteger; i++) {
        prmis.push(asyncProcess(someVariable));
    }
    return $.when.apply($, prmis);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top