Programming asynchronously: Promises

Promises are in many ways the logical next step from callback. A promise is just a special object that promise to either resolve, or throw an exception.
Promises are easy to use, and easy to make. For example this is how you use some kind of library that uses promises:

.then(response=>{/*method to deal with the response*/})
.catch(e=>{/* method to deal with the exception*/})

You can also run multiple promises at once, with the Promise.all() method; useful when you have to load a lot of different stuff, like for example when your app starts and you need to load a lot of stuff into redux / state. And you can chain the thens as long as you return a response in the one before it.
But the thing that is important to remember is that a promise will no do anything before you call .then() on it.
And this is how you define a promise:

new Promise(function(resolve, reject){
  let data = myAwesomeMethod()
  if(data) resolve(data)
  else reject(data)

There are also tools like bluebird that can ‘promisify’ callback based methods.
I think Promises are awesome, for a number of reasons. They formalize things much more than a callback based api does. And I personally think that Promise.all makes it much easier to avoid callback hell.

Leave a Reply