Originally published at Shubho.Dev
Async programming in JavaScript was scary for me. The only async paradigm I was comfortable with was jQuery's $...
For further actions, you may consider blocking this person and/or reporting abuse
Hi,
on your template, you seem to be enjoying the verbosity. If not, I recommend:
and since you are using arrow functions, do you always use parentheses? This:
becomes..
Wait, what?!
This:
.. easily becomes this:
Back to your promise template. Here's a much lighter version. You don't need to reject, you throw:
Then on this monstrosity:
Consider changing it into:
It also helps to familiarize with
async/await
constructs.You concluded that 'Promises are difficult'. Please try to understand the main reason they exist (I am not telling you that now, sorry) - you will then see they are not so difficult at all.
Thanks for reading. The verbosity was intentional. The point was to show how to use Promises while writing functions as a beginner. Using arrow functions surely uses less lines of code and I use that in my actual projects. However explaining Promises to my juniors using arrow function was always difficult. I am familiar with
async/await
constructs. I still prefer Promises and use it as much as possible. But my colleagues who came from Java background they preferredasync/await
more 😀Maybe the point of the article was to show how simple it is to wrap everything in a promise, but starting with the original:
And combining with your suggestion (and doing the same with reject):
We can see that the then is just returning the value from the original promise and the catch is also just rejecting with the already rejected value. That means we're just returning the original promise, which can be simplified to:
Which is just the
fn_to_get_roll_number_from_db
function.I'll tell you one thing, that Promise chain example you gave is one of the main reasons prefer other languages over JS. That can easy make some scary ugly monster code !
This isn't really a problem with JS. Like others have shown it can be significantly simplified.
Sure, I must say that at least the new Async Await is cleaner, which is somthing I've actually used much more than Promises, as I spend more time in Go
Seems like callback hell awaiting. Why not use
async
/await
?Thank you for your awesome post, I prefer
async/await
it's much more easier for me.