<h1>Example: Promise 02</h1>
<p>複数の非同期処理が完了したら値を表示する(5秒)。</p>
<div ng-app="myApp">
  <div ng-controller="myController">
    <button ng-click="get_all()">すべての情報を取得</button>
    <button ng-click="reset()">リセット</button>
    
    <p>{{ data1 }}</p>
    <p>{{ data2 }}</p>
  </div>
</div>
@import "bourbon";

body {
  padding: 1.5rem;
}
View Compiled
var service = angular.module("customServices", []);
service.factory('myService', ['$q', '$timeout', function($q, $timeout) {
  return {
    data1: function(){
      //deferのインスタンスを作る(お呪いのようなもの)
      var d = $q.defer();
      
      $timeout(function(){
        d.resolve("Data:1(3秒で取得完了)");
      }, 3000);
      
      //プロミスオブジェクトを返す
      return d.promise;
    },
    data2: function(){
      var d = $q.defer();
      
      $timeout(function(){
        d.resolve("Data:2(5秒で取得完了)");
      }, 5000);
      
      //プロミスオブジェクトを返す
      return d.promise;
    }
  }
}]);

var app = angular.module('myApp', ['customServices']);
app.controller('myController', ['$scope', '$q', 'myService', function($scope, $q, myService){
  
  $scope.get_all = function(){
    //処理中に表示するテキスト
    $scope.data1 = '取得中';
    $scope.data2 = '取得中';
    
    //$q.allを使って複数のPromiseオブジェクトを取得する
    $q.all([
      myService.data1(),
      myService.data2()
    ]).then(function(strs){
      //すべてのPromiseオブジェクトが取得できたら実行される
      $scope.data1 = strs[0];
      $scope.data2 = strs[1];
    });
  }
  
  $scope.reset = function(){
    $scope.data1 = '';
    $scope.data2 = '';
  }
}]);

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. //ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js