Chaining promises with promise all results in unexpected execution order

Viewed 85

Why does the following code print baz, done before 1, 2, 3?

const bar = () => Promise.resolve([1, 2, 3]);
const cat = e => {
  console.log(e);
  return Promise.resolve(e);
};
const foo = () =>
  bar()
    .then(arr => Promise.all(arr.map(e => cat(e))))
    .then(console.log("baz"));

foo().then(console.log("done"));

2 Answers

You are executing console.log() immediately instead of passing it to callback function in .then(). This will do it:

const bar = () => Promise.resolve([1, 2, 3]);

const cat = e => {
  console.log(e);
  return Promise.resolve(e);
};

const foo = () =>
  bar()
    .then(arr => Promise.all(arr.map(e => cat(e))))
    .then(() => console.log("baz"));
    
foo().then(() => console.log("done"));

You probably forgot to embed the console.log into arrow functions so their execution is properly deferred:

const bar = () => Promise.resolve([1, 2, 3]);
const cat = e => {
  console.log(e);
  return Promise.resolve(e);
};
const foo = () =>
  bar()
    .then(arr => Promise.all(arr.map(e => cat(e))))
    .then(() => console.log("baz"));

foo().then(() => console.log("done"));

Related