4 ms·
Hack has a more readable "fix" now, which will hopefully make it to JS in due course: async function getPeople() { concurrent { const members = awa
by xixixao 6y ago
Hack has a more readable "fix" now, which will hopefully make it to JS in due course:
async function getPeople() {
concurrent {
const members = await fetch("/members");
const nonMembers = await fetch("/non-members");
}
return members.concat(nonMembers);
}
- jakear 6y ago...why? Please, please, don’t add syntax to “fix” semantics that can already be elegantly expressed using existing constructs (Promise.all). Minimal-ish syntax is one of the few areas JS gets things right.
- xixixao 6y agoYour argument can be applied against await/async in general - it doesn’t allow anything Promises didn’t allow before. The reason is that it’s easy to make a mistake when destructuring the Promise.all call, and the Promise.all call doesn’t scale well (here dummy example, spot the bug) const [foo, baz, bar] = Promise.all([getFoo(), getBar(), getBaz()]) This is much more readable and less error prone: concurrent { const foo = await getFoo(); const bar = await getBar(); const baz = await getBaz(); }
- jakear 6y agoThere’s always a line and it must be drawn somewhere. Async/await allow for chaining deferred execution blocks without introducing deep syntactic nesting, at the cost of 2 keywords. In my opinion the benefits of flattening the language outweigh the costs of adding the keywords. The hack approach otoh introduces an entirely new syntax construct (tagged blocks), which declares variables that escape their initialization block (unexpected in the JS world post-let/const), and strongly leverages the existing hack execution model whereby all await’s in a single statement are executed concurrently. This execution model is incompatible with the rest of JS (hack disallows many styles of having multiple awaits in an expression, such as `await a && await b`), and at the end of the day what are the benefits? It executes a series of statements in parallel, exactly the same as Promise.all. If you’re concerned about mixing and matching declarations, maybe try let foo, bar, baz; await Promise.all([ foo = getFoo(), bar = getBar(), baz = getBaz()]) ? Edit: realized in the above example the variables remain of promise type, which isn’t great. One could alternatively do “getFoo().then(result => foo = result)”, but I agree this isn’t great either.