如何在具有异步操作WinJS的for循环之后执行操作

时间:2014-01-03 02:17:35

标签: javascript asynchronous winjs

我在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);

它的作用:它执行带有异步操作的代码块(SOAP WebService调用),在第二个线程中执行removeCapturesOfScreenWithIndexArray,

而我需要的是这个程序执行我的下一个动作(removeCapturesOfScreenWithIndexArray)只有当我在for循环中的所有动作都完成后,我认为它与promises主题有关但我没有这个明确,如何那样做???

1 个答案:

答案 0 :(得分:5)

如果您希望在承诺完成后发生某些事情,则需要附加到承诺then。如果您希望在完成多个承诺之后发生某些事情,您可以将承诺加入到单个组合承诺中,然后附加到组合承诺的then

您的代码也有一个错误,它捕获循环变量。这意味着deleteCapturesIndexArray.push(i)将始终推送arrayCaptures.length

这是两个问题的解决方法。

// 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);
});