0

I'm using Promise.all(tasks) to track the overall completion of my tasks executed in no particular order (which is my main aim). I also want to track individual tasks completion, how do I do that?

user1514042
  • 1,899
  • 7
  • 31
  • 57

2 Answers2

1

Nothing keeps you from attaching individual handlers as well awaiting them together:

let tasks = …;
for ([t, i] of tasks.entries())
    t.then(res => {
        console.log("task "+i+" completed with", res);
    }, err => {
        console.log("task "+i+" failed because", err);
    });
Promise.all(tasks).then(all => {
    console.log("all tasks completed");
}, err => {
    console.log("something failed");
});
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • would then() not force sequential execution? – user1514042 Jan 27 '16 at 15:29
  • Yes, it would force the `console.log`s to run after the respective promise settles. It doesn't force any order between the promises. Just try it on your `tasks`! – Bergi Jan 27 '16 at 15:30
1

Try using Array.prototype.map() to pass promises to Promise.all()

var promises = [Promise.resolve("a"), Promise.resolve("b")];

Promise.all(promises.map(function(p, index) {
  return p.then(function(data) {
    console.log("inside .map()", data, "index", index)
    return data
  }, function(err) {
    console.log(err);
    return err
  })
}))
.then(function(complete) {
  console.log("all promises after .map()", complete)
}, function(err) {
  console.log("err", err)
})
guest271314
  • 1
  • 15
  • 104
  • 177
  • That'll hardly ever hit `console.log("err", err)` early-reject, as you're handling all errors – Bergi Jan 27 '16 at 15:38
  • @Bergi Can describe "hardly ever hit console.log("err", err)" ? Will not reach `onRejected` of `.then` following `.all()` ? – guest271314 Jan 27 '16 at 15:41
  • Yes, it will not reach it when any of the `promises` is rejected. – Bergi Jan 27 '16 at 15:42
  • @Bergi Interestingly just tried with second promise converted to `.reject("b")` , `"all promises after .map() ["a", "b"]"` logged at `.then` `onFulfilled` https://jsfiddle.net/9gprLc7q/ ? Would expect expect `console.log("err", err)` to be called ? Any insight ? – guest271314 Jan 27 '16 at 15:45
  • 1
    @Bergi http://stackoverflow.com/questions/35042068/why-is-onrejected-not-called-following-promise-all-where-promise-reject-incl – guest271314 Jan 27 '16 at 15:56