简体   繁体   中英

Promises: combine single resolve methods and Promise.all()

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() ?

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

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); })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM