Jesus
Jesus

Reputation: 8576

How to execute an action after a for loop with asynchronous actions WinJS

I have this block of code on WinJS:

// Triggers SOAP requests depending of how many webServices are required for uploading all the pictures
for (var i = 0; i < arrayCaptures.length; i++) 
{
    callWS(arrayTextFieldValues[i], UID_KEY[7], arrayCaptures[i].name).then(function (response) 
    {
        if (response == true) 
        {
            //if true, we have store the id of the picture to delete
            deletedCapturesIndexesArray.push(i);
        }
    },
    function (error) { }
    );
}

//my next action comes after this for loop
removeCapturesOfScreenWithIndexArray(deletedCapturesIndexesArray);

What it does: it executes a block of code with an asyncronous actions (SOAP WebService calls) and in a second thread it executes removeCapturesOfScreenWithIndexArray,

And what I need is this program executing my next action (removeCapturesOfScreenWithIndexArray) only when all of my actions inside the for loop are finished, I think it has to do with promises topic but I don't have this clear, how to do that???

Upvotes: 2

Views: 275

Answers (1)

Raymond Chen
Raymond Chen

Reputation: 45173

If you want something to happen after a promise completes, you need to attach to the promise's then. If you want something to happen after several promises all complete, you can join the promises into a single combo-promise, and then attach to the then of the combo-promise.

Your code also has a bug wherein it captures the loop variable. This means that deleteCapturesIndexArray.push(i) will always push arrayCaptures.length.

Here's a fix for both problems.

// Triggers SOAP requests depending of how many webServices are required for uploading all the pictures
var promiseArray = arrayCaptures.map(function(capture, i) {
    return callWS(arrayTextFieldValues[i], UID_KEY[7], capture.name).then(function (response) 
    {
        if (response == true) 
        {
            //if true, we have store the id of the picture to delete
            deletedCapturesIndexesArray.push(i);
        }
    },
    function (error) { }
    );
});

// Run some more code after all the promises complete.
WinJS.Promise.join(promiseArray).then(function() {
    removeCapturesOfScreenWithIndexArray(deletedCapturesIndexesArray);
});

Upvotes: 5

Related Questions