Samantha J Samantha J - 2 months ago 5
TypeScript Question

How can I run a final piece of code before a $q.all returns?

I have code that runs promises

phrasesUpdate = (): ng.IPromise<any> => {
var self = this;
var promises = [];
angular.forEach(self.phrases, (ph, key) => {
if (ph.statusId == Status.Dirty) {
? promises.push(self.phraseUpdateSubmit(ph, key))
: promises.push(self.phraseAddSubmit(ph, key));
return self.$q.all(promises);

This code works, however I would like to run this code:

self.phrases.forEach(function (phrase, index) { phrase.index = index; })

inside of this function before returning.

Is there some way that I can fit this into the function?


Just add then:

return self.$q.all(promises).then(result => {
    // Your last thing goes here
    return result;

Re your edited question: I believe this is how you integrate that line into the code:

return self.$q.all(promises).then(result => {
    self.phrases.forEach(function (phrase, index) { phrase.index = index; });
    return result;

(I'm assuming here that the phraseUpdateSubmit and phraseAddSubmit modify self.phrases, which is why we're waiting to do this until after the promises they return complete.)