Promises in Javascript

Ankita Panigrahi
3 min readFeb 26, 2020

--

Promises: is used to handle asynchronous operations in Javascript.

What we are basically trying to achieve is synchronizing asynchronicity in Javascript

Before going with promise, let’s understand callbacks.

Callbacks

For JavaScript to know when an asynchronous operation has a result (a result being either returned data or an error that occurred during the operation), it points to a function that will be executed once that result is ready. This function is what we call a “callback function”. Mainly when we make external API calls, we would need callback and until we get our data, Javascript keeps doing its normal execution.

fetch('https://jsonplaceholder.typicode.com/todos/1', (error, response) => {
if (error) {
//Handle error
} else {
//go Nuts!
}

But if we have multiple callbacks when one function needs the data of the previous function. For example:

getData(function(x){
getMoreData(x, function(y){
getMoreData(y, function(z){
...
});
});
});

This is called callback hell.

Apart from complexity as we can see as the function grows, error handling is repeated for every callback and it will go haywire when we loop through asynchronous calls.

Here comes Promise as promised. 😆

Promises

It works the same way as a callback but makes the error handling less verbose by chaining the functions in resolve and reject state. Promises are asynchronous

let promise=new Promise((resolve,reject)=>{
setTimeout(()=>{
let error=false
if(!error)
resolve('Done')
else
reject('Not Done')
},1000)

promise
.then((data)=>console.log(data)) //Done
.catch((error)=>console.log(error))

Here the error variable is false, it is calling the then block of ‘promise’ through resolve and if an error would have been true it would have called the catch block and the output would have been ‘Not Done’

As seen in the above figure, a promise has three states

  1. Pending: when the results are computing. (initial state of each Promise)
  2. Resolved: the result was computed successfully
  3. Rejected: a failure occurred during computation.

A lot of asynchronous APIs are implemented using promise. E.g: Axios is a popular ‘Promise based HTTP client for the browser and node.js’

const axios = require(‘axios’);
axios.get(‘http://www.somepage.com')
.then(function (response) { // Reponse being the result of the first request
// Returns another promise to the next .then(..) in the chain
return axios.get(`http://www.somepage.com/${response.someValue}`);
})
.then(function response { // Reponse being the result of the second request
// Handle response
})
.catch(function (error) {
// Handle error.
});

We can also chain then block as shown above in which ‘response’ for each then block is coming from preceding request.

Promises helped to mitigate the callback hell but it still relies on callbacks in then and catch method. It paved a way for async-await in ECMAScript 2017 that proved to be the cherry on top for Promise. It allows us to write a promise-based code as if it is synchronous.

--

--

Ankita Panigrahi
Ankita Panigrahi

No responses yet