by megous · 7y ago · 0 comments
Instead of:
async function main() {
// code
}
main().catch(console.error);
I'll be maybe writing: try {
// code
} catch (ex) {
console.error(ex);
}
Hrm?To me this is most important in node where it's not uncommon to do async operations during initialization. Currently you either have to export a promise or an async function.
Is the argument for top-level await that you don't need the other spot? Because I feel like you still do - except now it's implicitly inside not only A, but likely B and C as well to some extent. And in a very inflexible way.
Synchronous effectful imports are already are the source of so much frustration, and now we're adding asynchronicity to it?
Just export a init function and let your users choose when/where to run your effectful initialization code, sync or async.
fetch(allResourcesUrl).then(async response => {
let allResources = await response.json();
let pageResource = await (await fetch(allResources.page1.url)).json();
// set up page with pageResource
});
can be replaced with {
let allResources = await (await fetch(allResourcesUrl)).json());
let pageResource = await (await fetch(allResources.page1.url)).json();
//set up page with pageResource
}
Note use of a top-level block instead of a function context to hide local variables. // code
Outputting errors to console is the default behavior.The only difference it will make here is to suppress the default stack trace[1] and errorlevel returned to the shell. If you are writing in this kind of "scripting" style, you probably don't want to suppress errorlevels, so leaving out the catch is not only simpler, it is safer.
[1] You may get a stack trace with an Error object, but not the default one from the Node process.
That's not necessarily the case (or maybe poorly worded), e.g.:
async function main() {
// code
setInterval(() => console.log('hey'), 1000)
}
main()
In real life, it would probably be a HTTP server holding up the process. It's true that you likely want to crash hard if you have unhandled error during server initialization but I would still catch the error because Node.js will otherwise print a bunch of ugly "UnhandledPromiseRejectionWarning" messages. E.g.: main().catch(err => {
console.error(err);
process.exit(1);
});
With top level async landing in v8, I guess Node.js will eventually stop printing those warning messages.There is also the original use case that the original proposal of needing to do async calls when during module loading.
const result = await db.events.find();
console.log(result);
That's my whole script void async function main() {
// code
}() (async () => {
// code
})().catch(console.error)Why is it needed here? To force an expression without using the parentheses?
Edit: Yes, it seems so, and this usage with functions is explicitly documented there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...