Contents hide 1) What Is JavaScript Promises ? 2) Javascript Promises States 2.1) A javascript promises can be in one of 3 states: 3) Promise Constructor 3.1) The API 4) Chaining Javascript Promises 5) Handling Errors 5.1) This is similar To : In this tutorial, We will Understanding What Is JavaScript Promises What Is JavaScript Promises ? A promise represents the eventual result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize. Promises provide a simpler alternative for executing, composing and managing asynchronous operations when compared to traditional callback-based approaches. They also allow you to handle asynchronous errors using approaches that are similar to synchronous try/catch. Javascript Promises States A javascript promises can be in one of 3 states: Pending : The outcome of the promises has not been determined because the result hasn’t completed produce by the asynchronous operation. Fulfilled : The asynchronous operation has completed, and the promise now has a value. Rejected : The asynchronous operation failed, and the promise will never be fulfilled. In the rejected state, a promise has a reason that indicates why the operation failed. Promise Constructor The API To get started, let’s examine the following code which creates a new Promise object. if (window.Promise) { // Check if the browser supports Promises or not var promise = new Promise(function(resolve, reject) { //asynchronous code goes here }); } Let’s start by instantiating a new Promise object and passing it a callback function. The callback takes two arguments, resolve and reject, which are both functions. All your asynchronous code goes inside that callback. If everything is successful, the promise is fulfilled by calling resolve(). In case of an error, reject() is called with an Error object. This indicates that the promise is rejected. Now let’s build something simple which shows how promises are used. The following code makes an asynchronous request to a web service that returns a random joke in JSON format. Let’s examine how promises are used here if (window.Promise) { console.log('Promise found'); var promise = new Promise(function(resolve, reject) { var request = new XMLHttpRequest(); request.open('GET', 'http://api.icndb.com/jokes/random'); request.onload = function() { if (request.status == 200) { resolve(request.response); // we got data here, so resolve the Promise } else { reject(Error(request.statusText)); // status is not 200 OK, so reject } }; request.onerror = function() { reject(Error('Error fetching data.')); // error occurred, reject the Promise }; request.send(); //send the request }); console.log('Asynchronous request made.'); promise.then(function(data) { console.log('Got data! Promise fulfilled.'); document.getElementsByTagName('body')[0].textContent = JSON.parse(data).value.joke; }, function(error) { console.log('Promise rejected.'); console.log(error.message); }); } else { console.log('Promise not available'); } The Promise constructor callback contains the asynchronous code used to get data the from remote service. Here, we just create an Ajax request to http://api.icndb.com/jokes/random which returns a random joke. When a JSON response is received from the remote server, it is passed to resolve(). In case of any error, reject() is called with an Error object. When we instantiate a Promise object we get a proxy to the data that will be available in future. In this case, we are expecting some data to be returned from the remote service at some point in future. So, how do we know when the data becomes available? This is where the Promise.then() function is used. This function takes two arguments: a success callback and a failure callback. These callbacks are called when the Promise is settled (i.e. either fulfilled or rejected). If the promise was fulfilled, the success callback will be fired with the actual data you passed to resolve(). If the promise was rejected, the failure callback will be called. Whatever you passed to reject() will be passed as an argument to this callback. Chaining Javascript Promises For instance, you might have multiple asynchronous operations to be performed. When one operation gives you data, you will start doing some other operation on that piece of data and so on. Promises can be chained together as demonstrated in the following example. function getPromise(url) { // return a Promise here // send an async request to the URL as a part of the promise // after getting the result, resolve the promise with it } var promise = getPromise('some url here'); promise.then(function(result) { //we have our result here return getPromise(result); //return a promise here again }).then(function(result) { //handle the final result }); The tricky part is that when you return a simple value inside then(), the next then() is called with that return value. But if you return a promise inside then(), the next then() waits on it and gets called when that promise is settled. Handling Errors You already know the then() function takes two callbacks as arguments. The second one will be called if the promise was rejected. But, we also have a catch() function which can be used to handle promise rejection. Have a look at the following code: promise.then(function(result) { console.log('Got data!', result); }).catch(function(error) { console.log('Error occurred!', error); }); This is similar To : promise.then(function(result) { console.log('Got data!', result); }).then(undefined, function(error) { console.log('Error occurred!', error); }); NOTE : if the promise was rejected and then() does not have a failure callback, the control will move forward to the next then() with a failure callback or the next catch(). Apart from explicit promise rejection, catch() is also called when an exception is thrown from the Promise constructor callback. So, you can also use catch() for logging purposes. Note that we could use try...catch to handle errors, but that is not necessary with promises as any asynchronous or synchronous error is always caught by catch() Refrence: HTML5Rocks Mozilla Developer Network Get More Post On JavaScript Share this:TwitterFacebookRedditLinkedInWhatsAppPrintTumblr Related Tags: JavaScript, javascript promises, js, promises