Promises

Promises is a construct that lets you deal with async calls in a very nice way. The fetch api for example is using promises. There really isn't much to it. Let's look at a few examples:

function doAsync(){
  return new Promise(( resolve, reject ) => {
    setTimeout(() => {
      if( condition ) {
        resolve('data')
      } else {
        reject('err')
      }
    }, timeoutInMiliseconds)
  });
}

doAsync().then(data => {

})
.catch(err => {

})

We instantiate a Promise object and give it a function in the constructor with the arguments resolve and reject which are functions. Depending on wether the async operation is considered to have succeeded you call resolve or if it has failed you call reject.

If you call resolve then the .then() method will be invoked. Calling reject means the catch() will be invoked instead.

Shorthand helpers

There also exist short hand versions of this such as

Promise.resolve('data')
Promise.reject('err')

This is when you know straight away what you want for kind of Promise. As you can see there is no need to instantiate a promise.

Multiple fetches

There also exist a method where you can perform many async operations at the same time that waits for each other to finish, namely:

Promise.all([
  getData()
  getMoreData()
  getEvenMoreData()
])
.then( resultsArray => {
  // do stuff with results
})

To read more about Promises I recommend Mozilla on Promises

results matching ""

    No results matching ""