Promises

In JavaScript, many actions are asynchronous. A great example of this is an AJAX request. When the request is sent, you do not know when or even if a request will be returned. This is where promises come in.

A promise is an object that will promise to run a function once an asynchronous event has happened. In our example, the event will be the request returning. This could be in a few milliseconds or longer, depending on the timeout setting.

In addition to tracking successful events, promises can be rejected. This allows the object that was waiting for the response to do something different.

Note

Visit https://promisesaplus.com/ for the complete specification for using promises in JavaScript. Promises or promise-like objects are applicable in almost any JavaScript that you may write.

$q

This is the service that implements promises:

$q.defer()

Return value

This returns a deferred object.

Description

This is the core of building and using promises. The first thing is to get a deferred object, which will have to resolve and reject functions. When the action is successful, call the resolve function; when it fails, call reject. Finally, return the promise with defer.promise.

With the promise, you can call then, which takes two functions. The first will be called when resolve is called, and the second will be called when reject is called. The promise can be passed around and have then called multiple times.

Anytime you are doing anything asynchronous, you should use promises. With Angular, you should use $q as it is tied in with rootscope.

Here is an example where a function will succeed when the number is even and fail when the number is odd. Then, it is executed twice, logging to the console, whether it succeeded or failed. Note that the function is created in the controller, but a utility function like this should be put a service into production:

firstModule.controller('SimpleController', ['$scope', '$q', function ($scope, $q) {
  function qTest(number) {
    console.log($q);
    var defer = $q.defer();

    if (number % 2 === 0) {
      defer.resolve(number);
    } else {
      defer.reject(number);
    }
    return defer.promise;
  };

  qTest(2)
    .then(function (n) { console.log('succeeded!'); }, function (n) { console.log('failed!'); });

  qTest(3)
    .then(function (n) { console.log('succeeded!'); }, function (n) { console.log('failed!'); });

}]);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.51.36