Over a million developers have joined DZone.

Making a Promise with JavaScript

DZone's Guide to

Making a Promise with JavaScript

· Web Dev Zone ·
Free Resource

Read this guide to learn everything you need to know about RPA, and how it can help you manage and automate your processes.

Chaining functions in javascript is fun, so is the understanding of Blocking vs Non-Blocking code, but callback can soon end up in hell!

To save one from callback hell, normally named functions are preferred as save boats, but promises are more promising patterns!

Promises are not new to the world of computer science, many JS frameworks have made promises for quite some time now, jQuery Deffered being one amongst them, taskjs is also very impressive.

Summarizing the promise in simple points :

  • An object that represents a one-time event, typically the outcome of an async task.

  • That function must return a promise, which can be fulfilled with a value or failed with an exception!

  • State transitions are performed based on the promises outcome.

  • Once the transition is done, it's state is frozen.

But normally there are more methods in it like :


Simple example :

var Promise = function() {} // Empty Promise ;)  
Promise.prototype.then = function (resolved, rejected) {
// Do a state transition, based on the result 
Promise.prototype.resolve = function (value) {
// Transit to resolved
Promise.prototype.reject = function (error) {
// Transit to rejected

Now we can make promises with a async block of code, like :

function doXHR(URL){
  //Mkae a promise 
  var promise = new Promise();
  var xhr = new XMLHttpRequest();
  // Register the event handler
    if(xhr.status === 200){
  // Make the XHR call.
  //Return the promise
  return promise;

We can now use the thus defined, function like :

doXHR(URL).then(function (data) {
  // Play with the data

Start making your promises!




Get the senior executive’s handbook of important trends, tips, and strategies to compete and win in the digital economy.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}