Skip to content

Instantly share code, notes, and snippets.

@JesterXL
Last active October 31, 2022 16:02
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JesterXL/7f066f5ffc4a8ab64541513f1357a65e to your computer and use it in GitHub Desktop.
Save JesterXL/7f066f5ffc4a8ab64541513f1357a65e to your computer and use it in GitHub Desktop.
Example of using Array Destructuring for Promise.all.
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;
});
@samartioli
Copy link

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)

var asyncArray = [];

var promiseObjects = {
    a: {
        promiseFunction: () => { return Promise...}
    },
    b: {
        promiseFunction: () => {return Promise...}
    },
    // ...
}

_.each(promiseObjects, (value, key) => {
    asyncArray.push({
        key: key,
        promise: value.promiseFunction(),
    });
});

Promise.all(_.map(asyncArray, x => {return x.promise;}))
    .then(resolvedPromisesArray => {
        _.each(resolvedPromisesArray, (resolvedPromise, index) => {
            promiseObjects[asyncArray[index].key].resolved = resolvedPromise;
        });
    })
    .catch(error => {
        console.log(error);
    })
;

@senyaak
Copy link

senyaak commented Jun 27, 2018

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

@tpickett
Copy link

let [first, second, third] = await Promise.all([
    someThingThatReturnsAPromise(),
    otherThingThatReturnsAPromise(),
    lastThingThatReturnsAPromise()
 ]);

but better still!

@aaronwbrown
Copy link

@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!

@Mihailoff
Copy link

@aaronwbrown try {} catch ?

@JesterXL
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment