by koolba · 9y ago · 0 comments
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.
We can refactor another round:
function logFsResult( type, err ){
var msg= '';
switch ( type ) {
case 'append': msg= ( err ) ? 'Failed to update file' : 'Successfully updated file';
break;
case 'write': msg= ( err ) ? 'Failed to write file' : 'Successfully created file';
break;
default: msg= 'logFsResult error, missing or invalid first argument: '+ (type || '')
}
( err ) ? console.err( msg ) : console.log( msg );
}
function handleFile( filename, fileExists ) {
const timestamp = new Date().toISOString();
( fileExists )
? fs.appendFile( filename, `Updated file on ${timestamp}\n`, logFsResult.bind(null, 'append') )
: fs.writeFile( filename, `Created file on ${timestamp}\n`, logFsResult.bind(null, 'write') );
}For example you could do something like this (sorry, don't have time to open my IDE to try the code i'm going to write):
logFsResult = (type, err) => {
map_action = {
"append": {
True: "Succesfully updated file.",
False: "Failed to update file."
},
"write": {
True: "Successfuly created file.",
False: "Failed to write file."
}
}
message = map_action[type][(err != null)] // obtain the message
method = (err)? console.err : console.log // choose logger
method(err) //invoke the correct logger with the message
}
This is an easier-to-mantain code. It separates the messages to use, from the logic. It allows you to easily configure/change the messages to log, and the method (function) for logging the error, without having to touch the decision logic. On your original example, the logic of the code was mingled with the error messages.You could say this example was more "idiomatic" ES2016.
[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.