Skip to content

How to properly iterate through array using async functions

I have an array of URLs, which I have to download using JS / Cordova async functions. My current implementation looks like this (simplified):

var urls = [ ...... many many ...... ]
var arrayPointer = 0;
downloadData();
function downloadData() {
    if(arrayPointer >= urls.length) {
        do_something_else();
        return false
    }
    downloadURL(urls[arrayPointer++],successDownloadCallback,failDownloadCallback);
    return false;
}
function failDownloadCallback() {
    logError();
    downloadData();
    return false;
}
function successDownloadCallback(data) {
   saveDataToFile(data,saveSuccessCallback,saveFailCallback);
   return false;
}
function saveFailCallback() {
    logError();
    downloadData();
    return false;
}
function saveSuccessCallback() {
    downloadData();
    return false;
}

Unfortunately, I get “Maximum call stack size exceeded” error sometimes. Is there a better way to do this?

Answer

I had this issue before and managed to resolved it by using async loop (for) here is an example

const downloadAllfiles = async (arr) => {
  for(const x of arr) {
     const file = await downloadURL(x.path);
     await saveFile(file);
  }
  console.log('done with all files');
}