Async JavaScript Part 2: Promises

'es6-promises'

This article is part of the Async JavaScript series, you can find the previous part on the following link: Async JavaScript Part 1: The Callback.

What is a Promise?

Promises make it easy for us to manage the asynchronous operation, they were designed to solve many of the problems we run into when using callbacks (you can read the first part about callbacks here) in our application. To be more precise, The Promise object represents completion or failure, of an asynchronous operation, and its resulting value. Promises are built on callback patterns so you need to understand how callbacks work before you can use them.

Let's see a simple example

const doWorkPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve(2)
  }, 1000)
})

So we have two functions named resolve and reject, if things went well and we got the result that we were expecting we call resolve, if things went bad we call reject.

doWorkPromise.then((result) => {
  console.log('success', result)
})

In the second part, we are using then() method, which allows us to register a function to run when things go well(when resolve is called), and we get access to the data from the first and only param (result). So these functions only get executed when things go well.

'success'
2

And we got the result of success and 2. In real life, things don't always go well, and sometimes we may call the reject() and pass the error message.

Let's see the second example

const doWorkPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('We have problems')
  }, 1000)
})

doWorkPromise.then((result) => {
  console.log('success', result)
}).catch((error) => {
  console.log('error', error)
})

If we call reject then() is not gonna run, it only runs when it is called resolve(). But we can chain on another method catch() that allows us to run a function when reject() is called. And we got:

'error'
'We have problems'

We can see in the image how they work 'promises-scheme'

In most of the cases, we won't create new promises but we will just be using then() and catch().

Let's see the third example

let promise = fetch('api/give-me-json');
promise.then((response) => {
  console.log(response)
}).catch((error) => {
  console.log(error)
})

There are clear advantages when working with promises, the code is much cleaner.

Next part: Async JavaScript Part 3: Async/Await.




#javascript #async #es6

Author: Aleksandar Vasilevski |

Loading...