Explain JavaScript promises Like I'm Five
Shubham Battoo

Shubham Battoo @shubhambattoo

About: Making the web with 100% recycled pixels.

Location:
India
Joined:
Oct 27, 2017

Explain JavaScript promises Like I'm Five

Publish Date: Jan 28 '18
18 7

Comments 7 total

  • Shubham Battoo
    Shubham BattooJan 29, 2018

    Thanks a lot.

  • Isaac Lyman
    Isaac LymanJan 29, 2018

    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()
    
    Enter fullscreen mode Exit fullscreen mode

    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))
    
    Enter fullscreen mode Exit fullscreen mode

    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))
    
    Enter fullscreen mode Exit fullscreen mode

    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)
    )
    
    Enter fullscreen mode Exit fullscreen mode
    • Shubham Battoo
      Shubham BattooJan 30, 2018

      Thanks for the response, very clear answer.

    • Chinmay Joshi
      Chinmay JoshiSep 21, 2018

      Thanks for the explanation. Helped me a lot.

  • Amit Merchant
    Amit MerchantJan 30, 2018

    Nothing is more simpler than this: scotch.io/tutorials/javascript-pro...

Add comment