4 ms·
Something to keep in mind: Javascript has a lot of obscure language idiom that aren't used in practice. This has to do with how the language was rushed into pro
by gwbas1c 7y ago
Something to keep in mind: Javascript has a lot of obscure language idiom that aren't used in practice. This has to do with how the language was rushed into production, and has gone through quite a lot of revisions.
This point is made in the (now very outdated) book "Javascript: The Good Parts," https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742 https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockfo.... Crockford, the author, brings you through the best way to write Javascript in 2008.
Related note: I once attended a talk from Crockford in 2010 where he was rather religious about how async code was significantly better than threads. I pointed out that async code is significantly harder to write due to the mess of callbacks, and his answer was quite rude. Now Javascript has async-await, which fixes the madness that comes from callbacks.
- 101404 7y agoAnd in between callbacks and asyncawait, it had Promises. I still often prefer those over asyncawait.
- eyelidlessness 7y agoAsync/await is semantically just sugar for promises (though implementations don't necessarily operate that way).
- fjp 7y agoI never wrapped my mind around the Promises API, but I have always async/await is much easier to grasp in any language
- pintxo 7y agoMaybe because it should have looked like this (personal opinion): waitForPromise() .then(handleResolve) .fail(handleReject) .catch(handleException); But actually looks like this: waitForPromise() .then(handleResolve, handleReject) .catch(handleException);
- csnover 7y agowaitForPromise().catch(foo) is exactly the same thing as waitForPromise().then(undefined, foo). Your first example is essentially the same as: waitForPromise() .then(handleResolve) .catch(handleReject) .catch(handleException); With the exception that if `handleResolve` also throws then that will be picked up by `handleReject`, whereas in `waitForPromise().then(handleResolve, handleReject).catch(handleException)` it won’t.
- pintxo 7y agoAnd you last sentence is exactly describing the issue I have. This merging of exception handling and rejection handling into one function call feels like a bad idea. As initially I thought catch() is only handling promise rejections. Then suddenly I ended up in the catch() although the Promise resolved fine, just to learn that my handleResolve code threw an exception. Unsurprisingly my handleReject code was not prepared for this.
- pintxo 7y agoThe value is in knowing when to use which.
- threatofrain 7y agoIn my mind callbacks abstract events and it's better to toss events into a more composable async pipeline than it is to write a body of code to ad-hoc handle a problem right there.