Welcome Guest! (App Version 3.1)

websitnero logo name

Promises

Promises in JavaScript

Promise is a simple object wrapping asynchronous operations which notifies whenever async operation is completed. It is exactly same as callback, but much simple and a tool to avaoid 'callback hell'.

As promise is an object, it has got its own methods to use to tell what to do incase of successful async call where data is fetched, or in case the execution failed and error is returned.

Note: "'then' method is used while making promise call if all goes right."

Note: "'catch' method is used in promise in case of errors"

alpha(param1, param2)
  .then(function(result){
    //do something with data
})
  .catch(function(error){
    //handle the error
})

Here, alpha is a function which will return a promise.

True potential of promise is seen where you have many asynchronous operations depending on each other and creating a messed-up callback hell.

Till the last version of HTML data could only be stored at client side in cookies which had a limit of 4KB. Now, webstorage can also be used to store data on the client side.

Note: "Promises are kind of solution to Callback Hell."

Following are 2 principles behind promise:

  1. A Promise provides control to the result of a callback -- either resolve or reject.
  2. All Promise objects have got a .then() method attached to them.

var promise = new Promise(function(resolve, reject) {
  // make async request, then...
  if (/* everthing goes well ... */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.