by miguelmota · 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.
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.
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...
It not only works for the main entrypoint module, but all other modules as well.
Though I can say I've ever encountered a reason to have that....
(function() { console.log('test'); })();
In old versions of JavaScript, variables had to be scoped to the nearest function (rather than the nearest block) so IIFE where often used for namespacing: var $ = (function() { this.version = '1.2.3'; })();
$.version; // 1.2.3
This worked because the function would be immediately invoked upon interpretation, scoping it's contents to itself (aliased by the variable name).A proper example of IIFE for lexical scoping would be something like this:
var numbers = "";
(function(){
for (var i=0; i<5; i++) {
numbers += i + " ";
}
})();
console.log(i) //undefined
Nowadays of course you could just use let instead of varYour code snippet would kind of work as expected if used as a constructor. As in:
var $ = function() { this.version = '1.2.3'; };
var obj = new $;
console.log(obj.version); //1.2.3
Of course that is not a IIFE.Ah...brings me back to my SO days...
var $ = new (function() { this.version = '1.2.3'; })();
console.log($.version); // '1.2.3'
EDIT:
Or if you really want to abuse the spec var $ = (function() { if (!(this instanceof arguments.callee)) return new arguments.callee(); this.version = '1.2.3' })();
console.log($.version); // '1.2.3'(function() { alert('swiggity swooty'); })();
It's a really neat pattern imo, I remember it fondly from my JS heavy days :)
According to this[1] exchange on Stack Overflow, the IIFE is used by TypeScript because of other scoping issues (specifically protecting class properties before instantiation and defining interfaces).
[0] https://yakovfain.com/2015/06/30/the-private-in-typescript-i...
[1] https://stackoverflow.com/questions/56086411/why-does-typesc...
(async () => { console.log(await 'hello world') })()