3 ms·
I wish we had syntax like concurrently { const user = await getUser(userId); const session = await getSession(sessionId); } meaning th
by dave4420 2y ago
I wish we had syntax like
concurrently {
const user = await getUser(userId);
const session = await getSession(sessionId);
}
meaning that
- the getUser and getSession calls occur concurrently (it desugars to Promise.all)
- user and session are available for use after the block
- user and session appear directly next to the calls that give them their values, unlike with Promise.all
- odyssey7 2y agoIt could get bloated rather quickly try { concurrently { const user = await getUser(userId); const session = await getSession(sessionId); } } catch (err) { … }
- filoeleven 2y agoThis doesn't seem too awful to do with a function instead, and doesn't require any new language syntax or features. async function concurrently(obj) { const kvlist = Object.entries(obj); const resolvedValues = await Promise.all( kvlist.map(([_key, promise]) => promise) ); return Object.fromEntries( kvlist.map(([key, _v], index) => [key, resolvedValues[index]]) ); } // Usage // This could also be const {user, session} = ... const info = await concurrently({ user: Promise.resolve(3), // or just 3 session: new Promise((resolve, reject) => { setTimeout(resolve, 100, "foo"); }), }); // info = {user: 3, session: 'foo'} You're left with having to get at your results via dot syntax, or having to duplicate the object keys to destructure them, but you'd have to do that with Promise.all() anyway. This lets you make the definitions declaratively.