Square Square - 2 months ago 19
Javascript Question

Promise in while loop javascript

I'm trying to generalize a script that encrypts forms using OpenPGP libraries.
I got some troubles with the client-side code (Javascript) :

var working = formID.elements[0];
var counter = 0;

while (working) {
encrypt(working.value).then(function(encrypted_msg) {
console.log("processing");
working.value = encrypted_msg;
});
console.log("assuming processed");
var counter = counter + 1;
var working = formID.elements[counter];
}


The following code should take each form element and encrypt its value. However, the while loop doesn't wait for the asynchronous encrypt() function to be resolved.

I think i need to use promises in this case, but i have no idea how and the few tutorials didn't work in a while loop.

Help ?

Answer

Probably can be used list of jQuery deferreds, something like this:

var deferreds = [];

$.each(formID.elements, function(key, working){

    var deferred = $.Deferred();
    deferreds.push(deferred);

    encrypt(working.value).then(function(encrypted_msg) {
        console.log("processing");
        working.value = encrypted_msg;
        deferred.resolve();
    });

});

$.when.apply( $, deferreds ).done(function(){
    console.log( 'after all encryptions!' );
});

Of course, can be used native Promise object instead $.Deferred, however I think $.Deferred is more cross-browser way.

UPD:

For the case when encrypt() returns correct promise may used more short and better way:

var promises = [];

$.each(formID.elements, function(key, working){

    var promise = encrypt(working.value);

    promise.then(function(encrypted_msg) {
        console.log("processing");
        working.value = encrypted_msg;
    });

    promises.push(promise);

});

Promise.all(promises).then(function(){
    console.log( 'after all encryptions!' );
});