For further actions, you may consider blocking this person and/or reporting abuse
Read next
2872. Maximum Number of K-Divisible Components
MD ARIFUL HAQUE -
Inceptive techniques to pull summaries and e-learning out of vocational training video series
Myles Dear -
Explaining Scoped Context in React with example
Pratik sharma -
OOP Simplified: Breaking Down the 4 Core Principles
Aayush Singh -
Top comments (7)
Suppose your friend asks you for a favor. "As soon as you get home from school," he says, "get online and reserve a copy of the new Sonic video game for me. If something bad happens and you can't come home today, call your mom and ask her to do it."
Your friend does not know when you will get home from school. He may not even care, as long as it happens. He wants you to complete some instructions whenever you arrive. And if something bad prevents you from getting home at all, he has a backup plan.
Meanwhile, since your friend has asked you to reserve the video game, he can work on other things.
Or, in plain JavaScript:
doOtherThings()
will probably be done beforereserveVideoGame()
oraskMomToReserveVideoGame()
ever happens, but there's no guarantee of that. Those functions could be called at any moment. The point is thatgetHomeFromSchool()
returns a Promise, and as soon as that promise completes (finishes what it was supposed to do or throws an error), the corresponding function will be called. You can be certain thatgetHomeFromSchool()
will be finished before anyone tries to reserve a video game. And if that Promise returns a value, it will be an argument to your callback functions.You can ask a Promise for several "favors":
You can return a Promise from a function and let the caller decide what to do with it.
You can also wait for multiple Promises to finish at a time (or any of them to throw an error):
Creating your own Promise in ES6 is pretty simple:
Thanks for the response, very clear answer.
Thanks for the explanation. Helped me a lot.
Nothing is more simpler than this: scotch.io/tutorials/javascript-pro...
Wow, this is really great!
It's not totally for five year olds, but it's damn close: dev.to/ardennl/about-promises-and-...
Thanks a lot.