Help us understand the problem. What is going on with this article?

Promises in AngularJS

More than 3 years have passed since last update.

Promises in AngularJS

Promises

Promises(約束) are objects which were proposed by ECMAScript 6. Their purpose is to run asynchronous operations. For example, if the part of a code needs a certain resource, it could load it in a promise, and resume the execution of this part of the code once the loading has completed. A promise can have three states:

  • :speech_balloon: Pending: The promise is still executing.
  • :o: Fulfilled: The promise has successfully completed.
  • :x: Rejected: The promise has completed with an error.

Implementation: The $q service

In AngularJS, promises are created using a service named $q. It is based on Q, an independant JavaScript library.

Example

Let's say we have a resource which takes some time to load. Instead of waiting for the loading to finish, we're going to load it asynchronously and only display it when it is available.
JSFiddle: http://jsfiddle.net/Maerig/4kg4ht29/

Create the promise

controller.js
function createLoadPromise() {
    var deferred = $q.defer();

    // Timeout to simulate the loading
    $timeout(function() {
        var resource = "Resource content";
        if(resource != null) {
            // Fulfilled: The promise has successfully completed.
            deferred.resolve(resource);               
        }
        else {
            // Rejected: The promise has completed with errors.
            deferred.reject("An error occured while loading the resource.")
        }
    }, 1000);

    return deferred.promise;
}

Use the promise

controller.js
$scope.loadResource = function() {
    $scope.resource = "Loading..."
    var promise = createLoadPromise();
    promise.then(function(resource) {
        $scope.resource = resource;                   
    }, function(error) {
        $scope.resource = "";                   
        alert(error);                   
    });
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away