In the postgres node module I stumbled over the following code:
async handle() {
!this.executed && (this.executed = true) && await 1 && this.handler(this)
}
I don't get understand the await 1
-part.
Can someone explain what is it good for?
Thx
CodePudding user response:
By using that construct, you can execute the latter function asynchronously, so other pending code in the event loop can execute.
await
is equivalent to promise.then
, which causes the resolving function of the promise to be executed in the next tick of the event loop.
function handler(n) {
console.log('handler', n);
return true;
}
async function fn() {
return handler(1) && await 1 && handler(2);
}
console.log('start');
fn();
console.log('end');
CodePudding user response:
This piece of engineering marvel is good as an example. It explains why in node/js you shouldn't write anything which is:
- Backend, and
- Longer than 10 lines of code
If you're really adventurous enough to determine why (!this.executed && this.executed = true) is not always false, then when you get to the callback spaghetti you should realize - there's no hope.
At the end there's some almost-good and almost-readable code. But that's a trap! this.handler(this) would be great, if the author removed this from the parameter. So close.
This single condition would be also great for writing a 200 pages book called "Programming for the brave" in which an expert could explain in details how this thing actually works and all the engineering decisions leading for this line of code to being born. And if that is code of database driver... meaning the cornerstone of application, i don't want to see how the code which is using it - have to look like...