by styfle · 9y ago · 0 comments
[0]: https://medium.com/@styfle/promises-in-node-js-8-x-core-d6a8...
function logAppendResult( err ) {
if (err) console.err('Failed to update file');
else console.log('Successfully updated file');
}
function logWriteResult( err ) {
if (err) console.err('Failed to create file');
else console.log('Successfully created file');
}
function handleFile( filename, fileExists ) {
const timestamp = new Date().toISOString();
( fileExists )
? fs.appendFile( filename, `Updated file on ${timestamp}\n`, logAppendResult )
: fs.writeFile( filename, `Created file on ${timestamp}\n`, logWriteResult );
}
function main() {
const filename = './example.txt';
exists( filename, (fileExists) => handleFile(filename, fileExists) );
}Well, who are we to deprive you from the joy of writing lots of boilerplate code?
(There are lots of other reasons to use the promise abstraction – having a type that can be transformed is extremely useful and natural – but that one’s pretty significant.)
if (err) console.err('Failed to create file');
Congratulations, you're writing Go in JavaScript! :)The real value for promises is async/await.
You've repeated the if(err) check in three places.
None of your error handling bubbles up so the handlers (i.e. Logging to console.error) are buried in the individual functions.
You've pretended to avoid nested callbacks by inlining them using arrow functions.
For your sake I hope that was sarcastic.
Inlining with arrows is just a more functional approach, as I would write in Coffee:
exists filename, (fileExists) -> handleFile filename, fileExists
Anything wrong with that line of code?I just try very hard to keep my code as simple as possible.
I hope you know it's trivial to write a log function that accepts different callees so you end up with only 1 'if (err)'.
I didn't test, but I wouldn't be surprised if my example runs times faster as well btw.
And if you replace the if(err) lines with a log(...) function it doesn't reduce them to one place. It makes you repeat the log(...) function everywhere. And you'd still need the if statement to handle the control flow.
Simple code is great, but not handling errors doesn't cut it for non throwaway applications.
[0]: https://github.com/nextorigin/el-borracho/blob/master/src/re...
P.S. Iced3 compiles to ES6 await so all of this has been working together for quite a while.
Using `try`/`catch` with `async`/`await` is a bit awkward, though, which is especially unfortunate because it's the #1 place you should be handling errors.
LightScript has a language feature[0] that makes it less awkward (sort of an`Either`/`Result` type) that I'm thinking about submitting to TC39.