Skip to content

The simplest JavaScript Promises examples

You might have heard the new buzz word Promises. I am not going to take long explaining Promises in this post, I will have another just on that topic. But for now, what you need to know is the following

  • Promise/A+ is the open standard for sound, interoperable JavaScript promises.
  • “Promise” in the A+ spec is defined as “an object or function with a then method whose behavior conforms to this specification”.
  • Promises present a great solution to address the complexities of asynchronous operations in JavaScript.
  • Promises are native with ECMAScript 6
  • Promises save you from the “CallBack Hell”
  • Promises have been implemented in numerous JavaScript libraries and many of which are complaint to the Promises/A+ spec.
  • It is available in WinJS but it adheres to the CommonJS/Promises proposal and still is not complaint to the Promises/A+ spec

I wanted to share with you the simplest example of an asynchronous call with Promises. The following code can be viewed in this JSFiddle as well

var promTest = function () {
return new Promise(function (resolve) {
setTimeout(resolve, 2000);
promTest().then(function () {
alert("and then?");
}, function (error) {
alert("i have errored");

The previous code is straightforward, we created a variable called promTest and assign it to a function that returns a new promise, we create a new promise that is resolved with a setTimeout after 2 seconds.
Then we call that promise with its then() method and pass it alert() in the success handler and alert(“i have errored”!) in the error handler.
Run the code in an HTML page or the above JSFiddle link and you will see it action.

Now how about a simple example that uses an XMLHttpRequest to make a web call and retrieve a JSON content  using promises. You can test it on this JSFiddle:
<div id="result" style="color: red;"> </div>

var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();'get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
} else {
getJSON('').then(function(data) {
// alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(error) { //error detection....
alert('Something went wrong.' + error);

The code is simple again, we define a function called getJSON that returns a promise, it makes an xhr call to a URL, this web call returns json retrieved in the result of the then() method after it succeeds, then we put that result in an div element for display. you can add/remove a letter from the URL to cause an error and see how it is alerted.

Published inWeb Development

Be First to Comment

Leave a Reply

Skip to toolbar