Promises examples in JQuery, Angular and Protractor

The JavaScript promises are one of the hardest subjects to learn from javascript. It is not the intent of this post to explain in deed what a promise is, we just gonna touch the basics, and see some examples of how to create our own promises with JQuery, AngularJs and Protractor

Topics:

  • Briefly explain what promises are
  • Promise examples
  • JQuery promise example
  • AngularJs/$q promise example
  • Protractor promise example
  • Working example in jsFiddle

What is a promise

A promise represents the eventual result of an asynchronous operation like a network call or a setTimeout function. It is a placeholder into which the successful result value or failure will materialize in a differed call.

Why Use Promises?

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.

Example of using the Promises

Here is a simple “hello world” program that synchronously obtains and logs a greeting.

var greeting = sayHello();
console.log(greeting);    // 'hello world’;

This code will be executed imperatively right after the asignation, it will excecute the console.log statement.
However, if sayHello is asynchronous and needs to look up the current greeting from a web service through the network for example, it may return a promise, and the code execution flow will continuing in parallel until the promise returns:

var greetingPromise = sayHelloAsync();
greetingPromise.then(function (greeting) {
    console.log(greeting);    // 'hello world’
//deferred response
});
console.log(“This statement will be excecuted before the then() callback”)

Examples:

JQuery example (see working example):

To illustrate this example we going to use setTimeout to simulate the delay in an asynchronous call.

//JQuery promise
function sayHelloAsync() {
  var deferred = $.Deferred();

 //the setTimeout will deffered the excecution of this function, and simulate how a network call works
  setTimeout(function() {
     deferred.resolve('Hello Word');//here we resolve the promise
  }, 5000);

  return deferred.promise();
}

var greetingPromise = sayHelloAsync();
greetingPromise.then(function(greetings){
   console.log(greetings)
});

console.log(“This statement will be excecuted before the then() callback”)

Angular $q example: Taken from the AngularJs documentation

function asyncGreet(name) {
  var deferred = $q.defer();

  setTimeout(function() {
    deferred.notify('About to greet ' + name + '.');

    if (okToGreet(name)) {
      deferred.resolve('Hello, ' + name + '!');
    } else {
      deferred.reject('Greeting ' + name + ' is not allowed.');
    }
  }, 1000);

  return deferred.promise;
}

var promise = asyncGreet('Robin Hood');
promise.then(function(greeting) {
  alert('Success: ' + greeting);
}, function(reason) {
  alert('Failed: ' + reason);
}, function(update) {
  alert('Got notification: ' + update);
});

Protractor syntax example:

function sayHelloAsync() {
  var deferred = protractor.promise.defer();

  setTimeout(function() {
     deferred.fulfill('Hello Word');//here we resolve the promise
  }, 5000);

  return deferred.promise;

}