0

I need my loop to wait for my function callback to iterate.

Here is my loop:

for(var i=0;i<tab.length;i++)
{
    this.fileService.download(tab[i]).then(success => {
        console.log("download : "+success);
    });
}
console.log("end");

for now my process just start the download and iterate, I want it to end the download function before iterate..

Thank you :)

Nico Baudon
  • 57
  • 1
  • 10
  • 1
    Does this answer your question? [Asynchronous Process inside a javascript for loop](https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop) – Liam Nov 15 '19 at 12:41
  • 3
    Your simplest option here is just to use `async` `await` – Liam Nov 15 '19 at 12:42

2 Answers2

1

You can do it like this:

Promise.all(tab.map(t => this.fileService.download(t)).then(success => {
    console.log("download : "+success);
});

But better solution here will be rxjs's Observable + async pipe

0

on every iteration of your for loop you're firing a promise, but you're not waiting for them to finish. You can do that using Promise.all

try

const promiseArr = tabs.map(tab => this.fileService.download(tab))
await Promise.all(promiseArr)
console.log('all files downloaded successfully')

Howeve Promise.all will only resolve if all promises in the array resolve, what if one of the promises in the array failed and you still want to do something after? For that you can use the new Promise.allSettled()

Khaled Osman
  • 1,251
  • 12
  • 17