问题
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