hkisthebest
hkisthebest

Reputation: 121

Is it a good practice to run async functions using for loop?

I have a function that uses spawn and calls ffmpeg to trim a file, which returns a Promise. I need to trim an audio file into multiple parts, so I iterate with a for loop which launches the trimming function, I only need the trimming process to complete (which generates the trimmed file) in the for loop (so I don't need to use await) but still need to make sure the trimming function did not return error.

for (let i = 0; i < myArray.length; i++) {
        trim().catch(console.error); //<--- Trim asynchronously
        linkedList.insertAtEnd(i); 
}

My problem is what is a good way to run the for loop trimming the audio asynchronously?

Edit: I don't want the trim() function to complete to iterate the next element in the array.

Edit: The difference between my question and this one is I don't want the for loop to wait for the trim() function in order to go on to the next element in the array.

Upvotes: 0

Views: 248

Answers (1)

crashmstr
crashmstr

Reputation: 28583

To know if there is any error, you need to deal with it at some point, and to do that, you need to know when they are all done, even if you do not want to wait on each before the next iteration of the loop.

To do this, either store each promise into an array (or use .map). You can then Promise.all to trigger code when each call of trim has completed.

I've added trim and myArray definitions and commented out the insertAtEnd for a "run-able" example (though having the linked list insert not being dependent on the trim makes little sense, nor does trim not taking any variants from the loop itself).

function trim() {
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve(), 5)
  });
}

let myArray = [1, 2, 3, 4];
let results = [];
for (let i = 0; i < myArray.length; i++) {
  results.push(trim().then(() => true).catch(() => false))
  console.log(`iteration ${i} finished`);
  //linkedList.insertAtEnd(i); 
}

Promise.all(results).then((r) => {
  console.log(`trim() results: ${r}`);
  if (r.every((x) => x)) {
    console.log('success');
  } else {
    console.log('an error occurred');
  }
});

Upvotes: 1

Related Questions