[AngularJS] Promises in controller. 1. $q.defer(), defer.resolve(), defer.reject(), promise.then().then()

Deferred represents a task that will finish in the future. We can get a new deferred object by calling the defer() function on the $q service.

Initially this task is in the status pending. Eventually the task completes successfully or it fails. In the former case the status of deferred will be resolved while in the latter case the status will be rejected. But who decides whether the task succeeds or fails, and how can this be achieved? Good question; the deferred object has two methods for this purpose. The first method resolve(…) is used to signal that the task has succeeded:

var defer = $q.defer();
defer.resolve("Success!!");

Note that the method has one parameter. Whoever calls the method resolve can pass any type of information which shall be the result of the task. It can be a simple type like a string or a number or a complex object. Thus this is also valid:

defer.resolve({id:1, firstName:"Zhentian", lastName:"Wan"});

The second method reject(…) is used to signal that the task has failed. The reject method also takes one parameter, the reason of the failure. Again the parameter can be a simple type like a string or a complex type like an Error object.

defer.reject('Sorry, I don't like you!');

or:

defer.reject(new Error("There is an error"));

Read More: 

http://lostechies.com/gabrielschenker/2014/02/04/angularjspart-11-promises/

 

 

What promises do is like check player result in O-Mopsi: First open game, then get game results, then get the player's result.

Using Angular Promises can handle that well.

var app = angular.module("app", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
        .when('/',
        {
            templateUrl: "app.html",
            controller: "AppCtrl"
        })
});
app.controller('AppCtrl',function($scope, $q){

    var defer = $q.defer();

    defer.promise
        .then(function(o){
            console.log("Open game: "+ o.gameId);
            console.log("check: "+ o.playerId);
            return {
                game: "game results",
                playerId: o.playerId
            }
        }).then(function(gameObj){
            console.log("Get player result");
            console.log(gameObj.game);
            console.log(gameObj.playerId);
            return "show playerRoute";
        }).then(function(str){
            $scope.model = {message: str};
            console.log("get str: "+str);
        });

    var data = {gameId: 475, playerId: 123};
    defer.resolve(data);
});

 

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="utf-8">
  <title>Egghead Videos</title>
  <link rel="stylesheet" href="./foundation.min.css">
  <script type="text/javascript" src="./angular.min.js"></script>
  <script type="text/javascript" src="./angular-route.min.js"></script>
  <script type="text/javascript" src="./app.js"></script>  
</head>
<body>

  <div ng-app="app">
    <ng-view></ng-view>
  </div>
</body>
</html>

 

<h1>{{model.message}}</h1>

 

RESULT> 

 

posted @ 2014-08-25 22:08  Zhentiw  阅读(1323)  评论(0)    收藏  举报