Promises explained

promise object is data returned by asynchronous function. It can be a resolve if the function returned successfully or a reject if function returned an error.

Promise: In JavaScript

JavaScript is single-threaded. Everything happens in the sequence it is written, line-by-line. But, asynchronous operations occur in the order they complete.

how you create a promise in JavaScript:


var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

The promise constructor takes in one argument: a callback function with two parameters — resolve and reject.

This promise can then be used like this:


promise.then(function(result) {
  console.log("Promise worked");
}, function(err) {
  console.log("Something broke");
});

If promise was successful, a resolve will happen and the console will log Promise worked, otherwiseSomething broke. That state between resolve and reject where a response hasn’t been received is pending state.

In short, there are 3 states to a promise:

  1. pending: awaiting promise response
  2. resolve : promise has successfully returned
  3. reject: failure occurred

Example1 : Using XMLHttpRequest object to make API Call

To fully understand the concept of promises, lets create an app which loads an image. If image is loaded, we will display the image, or else log an error.

First, lets create a promise using XMLHttpRequest(XHR).



// Import stylesheets
import './style.css';
// Write Javascript code!
const appDiv = document.getElementById('app');

const loadImage = function(url) {
  return new Promise(function(resolve, reject) {

    //Open a new XHR
    var request = new XMLHttpRequest();
    request.open('GET', url);

    // When the request loads, check whether it was successful
    request.onload = function() {
      if (request.status === 200) {
        // If successful, resolve the promise
        resolve(request.response);
      } else {
        // Otherwise, reject the promise
        reject(Error('An error occurred while loading image. error code:' + request.statusText));
      }
    };

    request.send();
  });

};
const embedImage = () => {
  loadImage('https://jsonplaceholder.typicode.com/todos/1').then(function(result) {
      appDiv.innerHTML = result;
    },
    function(err) {
      appDiv.innerHTML =  err;
      console.log(err);
    });
}

embedImage();

Example : Using Promise in javascript function call

cal = function(x,y) {
	console.log("x = " + x, "y = " + y);
	positiveSum(x,y).then(result => {
		console.log("sum = " + result);
	}).catch(err => {
		console.log(err)
		console.log("end of function");
})
}

positive = function(x,y) {
	return new Promise(function (resolve, reject) {
	if(x+y > 0){
		resolve(x+y)
} else {
	reject("Sum is less than zero")
}
})
}

cal(2,9)

Example 2 : Using Then Catch method to make API call



const getData = () => {
	return new Promise((res,rej)=>{
		fetch("https://jsonplaceholder.typicode.com/todos/1")
               //.then(response => response.json())
               .then(response => { return response.json()})
               .then(json => res(json.title));
         });
};

getData()
.then (resultProm => console.log(resultProm)) // delectus aum

Example 3 : Using Async/await

//A function return a promise 
const getData = () => {
	return new Promise((resolve,rej)=>{
		fetch("https://jsonplaceholder.typicode.com/todos/1")
               //.then(response => response.json())
               .then(response => { return response.json()})
               .then(json => resolve(json.title));
         });
};

//Using Then Catch method
getData()
.then (resultProm => console.log(resultProm)) // delectus aum

//Using Async/Await method
var resultStr = '';
var main = async()=>{
  resultStr = await getData();
  console.log('resultStr : ', resultStr)
}
main()
<div id="app"></div>

Click

Promise Reference

  1. Chain JS Promise
  2. async-await-vs-promises

  3. Promise Chain
  4. Mozila Promise
  5. Understanding JS Promise
  6. Promise Org
  7. Mastering Promise Angular2
  8. Promise Angular2 Youtube
  9. Promise VS RXJs Observable
  10. Promise Vs Observable Stack
  11. Promise For Asynchronous Programming
  12. Mastering Asynchronous
  13. Callback Vs Promise Vs Async await SitePoint
  14. Using Promise With Mongoose
  15. Switching Out Callback in Mongoose
  16. Nodejs Promise
  17. JS Promise and Error
  18. Codeburst
  19. Angular Promise DotnetGuru
  20. Promise instead of Callback in Mongoose
  21. Counting Promise Vs Rx

Leave a Reply

Your email address will not be published. Required fields are marked *