4 ms·
Brilliant and horrifying - I love it. It's a transpiler that puts "await" in front of every expression, resulting in code like: (async () => { async fun
by lioeters 5y ago
Brilliant and horrifying - I love it.
It's a transpiler that puts "await" in front of every expression, resulting in code like:
(async () => {
async function fetchPageBody(url) {
return await (await (await fetch)(await url)).text();
}
async function sleep(ms) {
return await new (await Promise)(await (async (resolve) => await (await setTimeout)(await (async () => await (await resolve)()), await ms)));
}
const body = await (await fetchPageBody)("https://enable-cors.org/");
const numDivs = (await ((await (await body).match(/<div/g)) || (await []))).length;
await (await console).log("Number of divs:", await numDivs);
await (await sleep)(2000);
await (await console).log("This prints after two seconds.");
})();
- protoduction 5y agoThat's right. And it also makes every function async. Literal expressions are not awaited - a tiny optimization ;)
- brundolf 5y agoI actually looked into this just yesterday because I was interested in doing this in my JS-targeted language :) As far as I can tell, the only real problem is performance. Wrapping synchronous expressions in Promise.resolve() (which is what this effectively does) is apparently not optimized out by V8, and is egregiously inefficient: https://madelinemiller.dev/blog/javascript-promise-overhead/ https://madelinemiller.dev/blog/javascript-promise-overhead/ For my use-case, probably what I'll end up doing is having the compiler be smart and only invisibly insert those asyncs/awaits where it actually needs to
- Jasper_ 5y agoBecause of how the microtask queue works, it can't optimize that out without introducing ordering issues. If you have two Promises, A and B, and each one has a callback that will then do another await, the implementation needs to interleave them, since microtasks are guaranteed to run in FIFO order. So a single await, even to resolve a constant expression, can't be omitted.
- brundolf 5y agoFair enough. In practice I think it's wildly dangerous to make those kinds of assumptions about async task ordering, but I can understand that engine authors have to follow the spec and don't have the luxury of dodging the issue.