[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 @   Zhentiw  阅读(1313)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示