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

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

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!




Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!


Published at DZone with permission of Hemanth HM, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}