rhysclay
rhysclay

Reputation: 1683

Return a promise when foreach loop ends

I'm wanting to run a forEach loop then return (resolve?) a Promise so that my next function can run. I can correctly work out when the forEach is at the end but just dont know how to resolve the Promise.

Here is my code:

  addSubmissionsForms(submissionId: string, submittedFields:Array<any>): Promise<any> {
    const submissionPath:firebase.database.Reference = this.rootRef.child(`submissionsByID/${submissionId}/fields`);

    submittedFields.forEach(function(submittedField, i) {    
      let fieldId = submittedField.id;
      submissionPath.child(fieldId).update(submittedField);
      if(i == submittedFields.length - 1) {
        console.log('finished');

      }
    });
  }

The reason I want to return a Promise is because I want to wait until this function has run then run another function like this:

  this.submissionsProvider.addSubmissionsForms(submissionKey, this.submittedFields)
  .then(() => {
    this.navCtrl.pop();
  });

Upvotes: 1

Views: 2342

Answers (1)

So if you want to use promises you can do the following:

As a side note you can resovle any value e.g. resolve('finished')

addSubmissionsForms(submissionId: string, submittedFields:Array<any>): Promise<any> {
    return new Promise((resolve, reject) => {
        const submissionPath:firebase.database.Reference = this.rootRef.child(`submissionsByID/${submissionId}/fields`);

        submittedFields.forEach(function(submittedField, i) {    
            let fieldId = submittedField.id;
            submissionPath.child(fieldId).update(submittedField);
            if (i == submittedFields.length - 1) {
                resolve();
            }
        });
    reject();
    });
}

If the function addSubmissionsForms does nothing async (like e.g. an ajax call or reading and writing into database) you don't really need promises because you just can execute functions one after another

addSubmissionsForms();
nextFunction();

Upvotes: 2

Related Questions