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..
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With