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 :)

2
  • 1
    Does this answer your question? Asynchronous Process inside a javascript for loop Commented Nov 15, 2019 at 12:41
  • 3
    Your simplest option here is just to use async await Commented Nov 15, 2019 at 12:42

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.