Abstract
Just like we can make use of the await
on async
functions. I suggest what I think is really simple, but very useful as well. A new way to await
over an array of promises.
A syntactic sugar for the old Promise.all()
The problem (AKA current implementation)
It's not uncommon to have something like this all across our code:
function getUser(id) {
return userStore.getById(id);
}
async function loadUsers(ids) {
const usersPromisesQueue = ids.map(async id => await getUser(id)); // usersPromisesQueue is now an array of promises that must be awaited
const users = await Promises.all(usersPromisesQueue);
return users;
}
Or you could say that I could simplify that as follow:
function loadUsers(ids) {
return Promises.all(ids.map(getUser));
}
But I suggest to make arrays "thenables" by default allowing us to just await
on them.
Because if you go with the first implementation, what is the better name for a usersPromisesQueue
?
Proposal
Just like an async function is just a syntactic sugar for a Promise. What about making await
over an array a syntactic sugar for the Promise.all()
. The exact same behavior.
So that our code could look just like:
async function loadUsers(ids) {
const users = await ids.map(async id => await getUser(id)); // notice the await directly executed over the result of the .map (an Array)
}
Or even better. What about:
function loadUsers(ids) {
return ids.map(getUser);
}
async function loadContext(usersIds, ...moreStuff) {
const users = await loadUsers(usersIds); // since the return of the loadUsers() function is an array. We could simply await on it.
// ... more stuff here
}
And the Polyfill for this will be pretty easy.
For me, this makes total sense. Because it makes the code a lot more readable.
So, I would like you guys to leve some comments. And PLMK what do you think