JavaScript || Promise – Resolve Promises In Order Of Completion Using Vanilla JavaScript

Print Friendly, PDF & Email

The return values of Promise.all are returned in the order that the Promises were passed in, regardless of completion order. Sometimes, it is nice to know which promise completed first.

The following is sample code which demonstrates how to resolve an array of promises and return the results in order of completion.

Contents

1. Resolve By Completion
2. Fail-Fast Behavior
3. Timeout
4. Utils.resolveByCompletion
5. More Examples


1. Resolve By Completion

The examples below demonstrate the return values of Promise.all compared to ‘resolve by completion‘.

‘Resolve by completion’ returns the completed values from fastest to slowest.



2. Fail-Fast Behavior

Promise.all is rejected if any of the elements are rejected. For example, if you pass in multiple promises that will resolve, and one promise that rejects, then Promise.all will reject immediately.

Similar to Promise.allSettled, ‘Resolve by completion’ allows returning the promises rejected value to the result list.

The following example demonstrates this behavior.

‘Resolve by completion’ returns the rejected value as apart of the result list, depending on the boolean ‘rejectOnError’ parameter.



3. Timeout

By default, ‘resolve by completion’ has no timeout. If setting a timeout is desired, it can be done like so.



4. Utils.resolveByCompletion

The following is Utils.resolveByCompletion. Include this in your project to start using!



5. More Examples

Below are more examples demonstrating the use of ‘Utils.resolveByCompletion’. Don’t forget to include the module when running the examples!

QUICK NOTES:
The highlighted lines are sections of interest to look out for.

The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.

Was this article helpful?
👍 YesNo

Leave a Reply