How to know if a promise inside a loop has ended?

Viewed 104

First of all, I'm sorry if this is a basic question, but I am not being able to do this. I have a promise that inserts data into a table (sqlite), and I have a for iterating over an array. I want to put all of that data into the table, but I want to know when it ends, to display a message at the end. I was verifying (i == array.length -1) it displayed the message but that doesn't seem correct. If I don't do this in this way the message displays before it has ended. I have two other promises that should run along this one and the solution(it seems a bad solution) above wouldn't work in this case, because one can end after or before the iteration. How can I know when they all are done too? Could you help me, please?

Here's my code:


 for (let i = 0; i < this.data_array.length; i++) {
    this.database.insertService(this.data_array[i]).then(async () => {
         console.log('Inserting object number ' + this.data_array[i].id);
           if( i == this.data_array.length - 1) {
              console.log('done!');
           }
     }).catch(err => console.log('error inserting object into the table'));
 }                  

Thank you.

4 Answers

It is a better practice to use Promise.all when dealing with such cases. A simple example would be the following:

let i;
let promises = [];
for (i = 0; i < 5; ++i)
     promises.push(someAsyncFunc(i));

Promise.all(promises)
     .then((results) => {
          console.log("All done", results);
     })
    .catch((e) => {
         console.log(e)
    });

You can solve this using Promise.all

Here is an example and here some useful documentation

the example is using map instead of a for loop to iterate over the array.

I haven't tested it but that should work

    Promise.all(
      this.data_array.map((data) => {
        console.log('Inserting object number ' + data.id);
        return this.database.insertService(data);
      })
    )
      .then((result) => console.log('done', result))
      .catch((error) => console.log(error));

You could use Promise.all([]) where .all() take an array.

Promise.all(
  // Map the items in data_array to the async insertService function
  this.data_array.map(dataEntry => this.database.insertService(dataEntry))
).then((resultArray) => {
  console.log(resultArray.length);
  console.log('done!');
}).catch((e) => {
     console.log(e)
});

I think that Promise.all is the best solution here

async method() {
  const promises = this.data_array.map(item => 
  this.database.insertService(item));
  try  {
    const result = await Promise.all(promises);
    console.log({ result });
  } catch (error) {
      console.log({ error });
  }
}
Related