Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..

like image 444
Aruna Avatar asked Aug 10 '26 19:08

Aruna


1 Answers

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);
like image 80
Malkus Avatar answered Aug 13 '26 10:08

Malkus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!