0

Explain JavaScript promises Like I'm Five

 2 years ago
source link: https://dev.to/shubhambattoo/explain-x-like-im-five-b92
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Discussion (7)

CollapseExpand

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:

getHomeFromSchool().then(function (response) {
  reserveVideoGame()
}, function(err) {
  askMomToReserveVideoGame()
})

doOtherThings()

doOtherThings() will probably be done before reserveVideoGame() or askMomToReserveVideoGame() ever happens, but there's no guarantee of that. Those functions could be called at any moment. The point is that getHomeFromSchool() 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 that getHomeFromSchool() 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":

var promise = getHomeFromSchool()
promise.then(() => reserveVideoGame())
promise.then(() => doChores())
promise.then(() => goToBandPractice())
promise.catch(err => callMom(err))

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):

var promise1 = getHomeFromSchool()
var promise2 = doChores()
Promise.all([promise1, promise2])
  .then(() => meetFriendsAtWendys(), err => callMom(err))

Creating your own Promise in ES6 is pretty simple:

var promise = new Promise((resolve, reject) => {
  // Let's say callApi uses old-school callback syntax
  callApi(response => resolve(response), err => reject(err))
})
promise.then(
  response => console.log('The API replied:', response),
  err => console.error('The API had an error:', err)
)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK