Good evening, fellows!
Let's simplify the use of Promises?
Particularly, when I started with the concept of Promises when I learned how to code, I saw a lot of online materials and tutorials that explained Promises in a very confusing way, then I decided to write a simple text explaining it in a very practical way. Of course, if you need to understand 'Promises Under the Hood' this article is not for you. If you need to understand Promises in a short period of time to make a solution, this is for you.
Basically, Promises were made to create better asynchronous callback functions in Javascript, to make the code better organized. To grasp the concept think like it literally means that we are making a promise in real life. For example:
- I promise that I will make you understand Promises in 15 minutes.
For that promise, I can do two things:
- I can either succeed by making you understand Promises in 15 minutes.
- Or I can fail and you'll not understand Promises in 15 minutes.
In code, it's the very same thing. Ok, so let's see this.
The output for this script is: This is in then: success
Here, we have a block inside of a Promise function that sums 1 + 1. If the result is 2, it means that our promise succeded, otherwise, means that our promise was rejected, because 1 + 1 = 2
. If we change the number of the sum, we'll be rejected because we're saying that the variable of the sum is 2. If it isn't, promise rejected.
The output for this script is: This is in catch: failed.
Now let's analyze this code
This code sees if you're using Angular or Vue, if one of those is true, it calls a callback function which sends an alert with a title and a message.
Now let's change this to a Promise and make this code better.
First, we create a function that instantiates a Promise, passing our parameters resolve and reject. Then, we write the code that we want to be in that Promise, in my case, I want to ensure that developers are using the React lib. So I make the validation and dispatch the action that I want to execute when the promise resolves and when the promise rejects. Like this:
After that, I write the then function calling my Promise and I can do whatever I want in that block. When that Promise is completed, I want to log a message in my console both when I have a resolution or rejection. In the THEN block is the code that runs when my promise is Resolved, and in the CATCH block, the one which runs when my promise is rejected.
Nice, huh?
Also, we can make simultaneous Promises using Promise.ALL when we need to make two or more Promises at the same time.
The output is going to be
Or use Promise.RACE if we need to get the result of the first Promise that executes and ignore the upcoming promises.
The output is going to be
And I guess that's it!
Some references:
- https://treinamento.nodebr.org/
- https://braziljs.org/artigos/promises-no-javascript/
- https://dev.to/khaosdoctor/entendendo-promises-de-uma-vez-por-todas-44i7
- https://dev.to/khaosdoctor/construindo-uma-promise-do-zero-4ndp
- https://imasters.com.br/javascript/futuro-das-promises-no-javascript
- https://www.youtube.com/watch?v=wZwMVbgQZps&list=PLnOICPAPShyRZd7nnbC7h8kCQwM-6K3KW&index=10&t=0s
Thank you!
Top comments (20)
Just be careful with
Promise.all
, if one promise fails, then all are considered rejected. IMO, using Promise.allSettled is a better approach - but also a much newer method.Thanks for the tip, never have I ever use Promise.allSettled. But I'm working in part 2 with more details about Promises. ;)
Great tip as well! I never knew that this existed, thanks. I'm just starting out on the new ES version
Good post! If anyone is interested, I wrote an interactive promises post long ago here: davydm.blogspot.com/2015/07/callba...
It gives some insight into promise usage and interoperability - different promise implementations (native, jQuery, q, bluebird, others) work together because of duck-typing - as well as a look at building your own implementation. I've built my own implementation of promises more than once - mostly for interest, but twice (re-coded from scratch when the architecture made fixing a particular bug near impossible) for synchronous-promise, an implementation of promises which doesn't background, on purpose, originally to make async testing easier, but it turns out people have found other uses for it.
I've been meaning to port the blog post above to dev.to (it uses an iframe to get the interactive content loaded from GitHub - so you can check out the source there too)
Thank you for the comment and for sharing your post! I’d love to read it 😉
Great! I learned a lot not in 15 minutes but just 5 😊
promise accomplished haha
Thank you!
Good article, I thought I didn’t understand promises well until I read your post. With each explanation and example there was, “yup”. Promise.all, Settled and .RACE are new concepts for me. Well done.
Thank you for the comment!! Sometimes we just need a simple abstraction to understand concepts in programming. I’m glad you liked ❤️
Great, love the text. Which tool do you use to create these screen shots? They're so amazing
Thank you! I’ve used carbon.now.sh.
thanks!! =) awesome tool!! love it
Please do one for observables?
Sure !
Great simple explanation, the programming world can use more articles like these! 🙌
thank you so much! ;)
Great tutorial. Thumbs up cause I really learned it in less than 15minutes with your article!
YAAY, thanks a lot!
Excellent! helped me to get a contrasting idea of promise and callback
Glad you liked ;)