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

Jes*_*sus 2 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);
Run Code Online (Sandbox Code Playgroud)

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

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

Ray*_*hen 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);
});
Run Code Online (Sandbox Code Playgroud)