wait for async function in loop to finish executing before next iteration

爱⌒轻易说出口 提交于 2019-12-12 13:29:34

问题


I have an array of image urls to download asynchronously. I need to wait the next iteration until the first async task completed. Here is my code snippet:

 downloadQueue.forEach(function (download, idex) {

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

After download completion of the first url, next one(iteration) should be started. How should i modified this code to get work on that? Any help..


回答1:


You will want to do something recursive.

That way you only start the next download after the promise returns from the download.

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


来源:https://stackoverflow.com/questions/32740236/wait-for-async-function-in-loop-to-finish-executing-before-next-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!