Last active
October 31, 2022 16:02
-
-
Save JesterXL/7f066f5ffc4a8ab64541513f1357a65e to your computer and use it in GitHub Desktop.
Example of using Array Destructuring for Promise.all.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Promise.all([ | |
someThingThatReturnsAPromise(), | |
otherThingThatReturnsAPromise(), | |
lastThingThatReturnsAPromise() | |
]) | |
.then( results => | |
{ | |
// this... | |
const [first, second, third] = results; | |
// ... instead of | |
// const first = results[0].result; | |
// const second = results[1].result; | |
// const third = results[2].result; | |
}); |
Promise.all([
someThingThatReturnsAPromise(),
otherThingThatReturnsAPromise(),
lastThingThatReturnsAPromise()
])
// this...
.then( ([first, second, third]) =>
{
// ... instead of
// const [first, second, third] = results;
// and
// const first = results[0].result;
// const second = results[1].result;
// const third = results[2].result;
});
much better
let [first, second, third] = await Promise.all([
someThingThatReturnsAPromise(),
otherThingThatReturnsAPromise(),
lastThingThatReturnsAPromise()
]);
but better still!
@tpickett - I am yet to find a clean way to handle errors when using array destructuring on a Promise.all. Do you have a pattern you follow that works well, without getting: "(intermediate value) is not iterable"
as an uncaught exception?
Thanks!
@aaronwbrown try {} catch
?
@aaronwbrown First, make Promises that don't fail: https://medium.com/@jesterxl/promises-that-dont-fail-bd1fd6139b97
Then you can use async/await without worry: http://jessewarden.com/2017/11/easier-error-handling-using-asyncawait.html
The basics as to why: http://jessewarden.com/2017/11/error-handling-strategies.html
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I use the paradigm above if I know the order of the Promises I am executing.
For more dynamic situations I have adopted the following (Since Hashs aren't iterable)