LoginSignup
0
0

More than 5 years have passed since last update.

Promises in AngularJS

Last updated at Posted at 2017-03-22

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);                   
    });
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0