Tuesday, December 25, 2018

Understanding Promise In Javascript

In this tutorial, we are going to discuss what is promise and how to use in javascript application. A promise is an object that represents an action that hasn’t finished yet but will do at some point in the future. It is essentially a placeholder for the result of some kind of asynchronous operation like a HTTP request.

PROMISE STATES

A promise can be in either one of these three states:
  1. Pending — Initial state, neither fulfilled nor rejected.
  2. Fulfilled — Successful completion of the operation.
  3. Rejected — A failure occurred during the operation. Rejected with a reason(error).
Understanding Promise In Javascript

The new Promise() constructor should only be used for legacy async tasks, like usage of setTimeout or XMLHttpRequest. A new Promise is created with the new keyword and the promise provides resolve and reject functions to the provided callback:

Lets see the sample example for promise :
var p = new Promise(function(resolve, reject) {
 
 // Do an async task async task and then...

 if(/* good condition */) {
  resolve('Success!');
 }
 else {
  reject('Failure!');
 }
});

p.then(function() { 
 /* do something with the result */
}).catch(function() {
 /* error :( */
})

Promise with Asynchronous call :

Lets see the simple example for promise, where we are using with XMLHttpRequest request in javascript.
function fetchData(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', url);

    req.onload = function() {
      // This is called even on 404 etc
      // so check the status
      if (req.status == 200) {
        // Resolve the promise with the response text
        resolve(req.response);
      }
      else {
        // Otherwise reject with the status text
        // which will hopefully be a meaningful error
        reject(Error(req.statusText));
      }
    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

// Use it!
fetchData('https://randomuser.me/api/').then(function(response) {
  console.log("Success!", response);
}, function(error) {
  console.error("Failed!", error);
});

Promise.all

The Promise.all method takes an array of promises and fires one callback once they are all resolved:

Synatx :
Promise.all([promise1, promise2]).then(function(results) {
 // Both promises resolved
})
.catch(function(error) {
 // One or more promises was rejected
});

Dealing with resolve. If any all promise are resolved, then it will fire the result in callback function.
var req1 = new Promise(function(resolve, reject) { 
 // A mock async action using setTimeout
 setTimeout(function() { resolve('First!'); }, 4000);
});
var req2 = new Promise(function(resolve, reject) { 
 // A mock async action using setTimeout
 setTimeout(function() { resolve('Second!'); }, 3000);
});
Promise.all([req1, req2]).then(function(results) {
 console.log('Then: ', results);
}).catch(function(err) {
 console.log('Catch: ', err);
});

Output :
-------------------
> "Then: " Array ["First!", "Second!"]

Dealing with rejection. If any promise is rejected the catch fires for the first rejection:
var req1 = new Promise(function(resolve, reject) { 
 // A mock async action using setTimeout
 setTimeout(function() { resolve('First!'); }, 4000);
});
var req2 = new Promise(function(resolve, reject) { 
 // A mock async action using setTimeout
 setTimeout(function() { reject('Second!'); }, 3000);
});
Promise.all([req1, req2]).then(function(results) {
 console.log('Then: ', results);
}).catch(function(err) {
 console.log('Catch: ', err);
});

Output :
-------------------
> "Catch: " "Second!"

Promise.race

Promise.race triggers as soon as any promise in the array is resolved or rejected:

Synatx :
Promise.race([promise1, promise2]).then(function(results) {
 // Both promises resolved
})
.catch(function(error) {
 // One or more promises was rejected
});

Lets see the simple example for promise with race condition.
var req1 = new Promise(function(resolve, reject) { 
 // A mock async action using setTimeout
 setTimeout(function() { resolve('First!'); }, 8000);
});
var req2 = new Promise(function(resolve, reject) { 
 // A mock async action using setTimeout
 setTimeout(function() { resolve('Second!'); }, 3000);
});
Promise.race([req1, req2]).then(function(one) {
 console.log('Then: ', one);
}).catch(function(one, two) {
 console.log('Catch: ', one);
});

Output :
-------------------
> "Then: " "Second!"

This is all about promise in javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

No comments:

Post a Comment