Async let/const declarations


#1

Typically to load a few async calls in parallel we’d use Promise.all(). Using a destructured declaration we can also load each result in to a separate variable, e.g.:

const [foo, bar, baz, ban] = await Promise.all([
    getThing(),
    loadStuff(),
    fetchItem(),
    requestObject()
]);

However this doesn’t have great readability. For example it’s not immediately clear that baz is assigned the result of awaiting fetchItem(), because the declarations and promises don’t line up. You have to count how far along they are and match them up.

They can be written out with await so that the declarations and promises line up, e.g.:

const foo = await getThing(),
    bar = await loadStuff(),
    baz = await fetchItem(),
    ban = await requestObject();

Unfortunately this then awaits sequentially. Promise.all() has a major performance advantage in being able to run them in parallel.

What if we could mark this declaration to load in parallel too? For example, using async const:

async const foo = await getThing(),
    bar = await loadStuff(),
    baz = await fetchItem(),
    ban = await requestObject();

This would then load them all in parallel just like Promise.all(), and now the declarations and promises line up, improving the readability.

Perhaps a better name would be parallel const, but this is bikeshedding.


#2

I’ve asked a similar question on ES Discuss last year:

https://esdiscuss.org/topic/would-it-be-possible-to-add-await-on-first-use-to-the-language