4 ms·
I still don't get the need for Promises.. Almost all examples, just like this one in the provided link, talk about solving callback hell with Promises, while ca
by twii 9y ago
I still don't get the need for Promises.. Almost all examples, just like this one in the provided link, talk about solving callback hell with Promises, while callback hell is just a bad way of writing software imao. Look at the code below and please tell me why your example with Promises is a better solution.
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) );
}
- koolba 9y agoIs this a joke? 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.
- twii 9y agoNo, it's not a joke. A junior dev can read this code and it will be very hard to create bugs. 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.
- doublerebel 9y agoYou might like the make_esc/errify pattern [0]. You can apply the same function to any number of error callbacks in order to unify error handling. Works great with Iced CoffeeScript but also works well without. I can provide more examples but I think you'll get it. [0]: https://github.com/nextorigin/el-borracho/blob/master/src/redis-model.coffee#L17 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.
- koolba 9y agoYes it doesn't handle the error case. 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.
- twii 9y agoYou assume a lot. 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') ); }
- koolba 9y agoHonestly that looks hideous.
- dchest 9y agoThat's still not error handling, that's error logging. Try writing code that depends on the success of the previous operation to perform another operation and you'll quickly find yourself in the callback soup.
- flavio81 9y agoWhenever you program in ECMAScript2016("Javascript"), you should take advantage of its features. Right now you're coding pretty much using the same way one would do it in C. Take advantage that functions are first-class in ES2016. Take advantage of JSON. 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.
- floatboth 9y agoif (err) console.err('Failed to create file'); Congratulations, you're writing Go in JavaScript! :)
- twii 9y agonah, this is valid javascript, Go came later, they might have copied a thing or 2 from C, like javascript did.
- flavio81 9y agoTakes a look at the code... logAppendResult almost same as logWriteResult... Well, who are we to deprive you from the joy of writing lots of boilerplate code?
- ujal 9y agoWith Promises we conceptualize a control flow construct like callbacks. It is much easier to reason about a concept rather than following code execution paths. With async await we return control flow to the current scope.
- elmigranto 9y agoWhen callbacks are used with discipline, they are not much different from promises. The problem is when "discipline" part meets "human" part, though it's still true for promises, perhaps to a lesser degree. The real value for promises is async/await.
- minitech 9y agoHave you ever tried to run more than one operation at once and collect the results? (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.)
- rattray 9y agoOne benefit comes from being able to use `async`/`await`. 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. [0] – http://www.lightscript.org/docs/#safe-await http://www.lightscript.org/docs/#safe-await
- tlear 9y agoI will agree, to be honest I tried promises in my own projects and now writing them for someone. But to me Async.js is just cleaner nicer better. Funniest part is Bluebird docs on transitioning from it to Promises, promise example is bigger and messier.