等待循环中的异步函数在下一次迭代之前完成执行

时间:2015-09-23 12:56:35

标签: angularjs asynchronous angular-promise

我有一组图片网址可以异步下载。我需要等待下一次迭代,直到完成第一个异步任务。这是我的代码片段:

 For i = 1 To oSel.Count         ' Loop through all the currently .selected items
    Set oItem = oSel.Item(i)    ' Get a selected item.
 Next i

下载完成第一个url后,应启动下一个(迭代)。我应该如何修改此代码以获得相关的工作?任何帮助..

1 个答案:

答案 0 :(得分:3)

你会想要做一些递归的事情。

这样,您只能在承诺从下载返回后开始下一次下载。

//Declare the recursive function
var startDownload = function(downloadQueue,i) {
    download.startAsync().then(
        function (res) { console.log('onSuccess'); },
            function (err) { console.log('onError'); },
            function (msg) {
            var progressPrecent = parseFloat(msg.bytesReceived / msg.totalBytesToReceive * 100).toFixed(2);
            console.log('Progress: ' + progressPrecent);

            //If there are more items to download call startDownload
            if(i < downloadQueue.length) {
               startDownload(download,i+1);
            }
    });
}

//Initialize Function
startDownload(downloadQueue,0);