等待循环中的异步函数在下一次迭代之前完成执行
wait for async function in loop to finish executing before next iteration
我有一组图像 url 要异步下载。我需要等待下一次迭代,直到第一个异步任务完成。这是我的代码片段:
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);
});
});
第一个 url 下载完成后,应该开始下一个(迭代)。我应该如何修改这段代码才能开始工作?任何帮助..
你会想做一些递归的事情。
这样一来,您只有在承诺 returns 下载后才开始下一次下载。
//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);
我有一组图像 url 要异步下载。我需要等待下一次迭代,直到第一个异步任务完成。这是我的代码片段:
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);
});
});
第一个 url 下载完成后,应该开始下一个(迭代)。我应该如何修改这段代码才能开始工作?任何帮助..
你会想做一些递归的事情。
这样一来,您只有在承诺 returns 下载后才开始下一次下载。
//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);