Storing the results of async/await functions executed in parallel
Ever since Node 8 became the new LTS and the default runtime for AWS Lambda, I’ve loved using the async/await syntax: it’s super legible and allows for much easier conditional promise chaining than the previous native alternatives.
Before too long I found myself wanting to execute a large selection of functions at the same time and continue only when all were complete. And, of course, some very smart people on StackOverflow had already considered this and some even smarter people had written a selection of fantastic answers. For a time, all was well.
But then I found myself in a scenario whereby I needed to store the result of each Promise (e.g. retrieving an array of objects from S3 or, in my use-case, retrieving an array of shadows from AWS IoT). Here is my first attempt:
Hmm… not very helpful. Even though I’m using the
Promise.all approach, because of the inline
await the promises are happening sequentially (hence the
b:210when it should in fact be the same time as
a ). In my use-case, this is what I got:
At first I blamed AWS (as I make a habit of doing several times per day) then I blamed Node but then I began to wonder if maybe I was just being a n00b — and yes, that was the problem.
then … Yes
.then() ! I thought that particular function was long gone in favour of
await -ing but perhaps it could still be of use.
My next attempt was far, far more successful:
Perfect! And the actual result:
And there you have it — maybe it’s the right way, maybe it’s not but it works and I was so overjoyed by this discovery I rushed right hope to write about it.
I hope my post-gym rambling can save a few of you a little headache when you’re dealing with