0

I have multiple promises fetching different assets. I want to achieve:

  1. Executing some code first to handle some of these promises via then().
  2. When everything is resolved/fetched, executing some code that launches my app via Promise.all().then().

I need to make sure 1 is excuted before 2. It does seem to work from what I have tested.

// handle promises one by one
promise1.then(results => {});
promise2.then(results => {});

// common process that should come after the above then()s
Promise.all([promise1, promise2])
    .then(results => {});

But can I rely on it? Are "single" then() always executed before a then() on Promise.all()?

Yosko
  • 329
  • 1
  • 4
  • 15

2 Answers2

4

While Promise.all is stalled because it waits for all the promises to finish, there is no guarantee that it will resolve after the .then call on the promise that resolves last.

Instead you should try creating new promises from the .then calls.

// handle promises one by one
const promise3 = promise1.then(results => {});
const promise4 = promise2.then(results => {});

// common process that should come after the above then()s
Promise.all([promise3, promise4])
    .then(results => {});

This way you can guarantee that the Promise all will resolve after the then calls

Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30
  • That's the solution I had in mind to overcome this in case my approach wasn't enough. Thank you. – Yosko Oct 25 '21 at 08:53
1

You can around by using Async/await. With waiting for each promise, you can write code to process data at the end.

Example:

(async () => {
  const responses = [];
  await new Promise((res) => res("promise1")).then((res) => {
    console.log("From promise1 first then");
    responses.push(res);
  });

  // Code at the end to do after all promises
  console.log("Coming from second");
  console.log("Responses:", responses);
})();
MrCeRaYA
  • 581
  • 4
  • 6