var ngApp = angular.module('ngApp', []); // $q爲內置服務 ngApp.factory('UserInfoService', ['http','$q', function($http, $q) { return { query: function() { var defer = $q.defer(); //聲明延後執行 $http({method: 'GET', url: 'data/students.json'}) .success(function(data, status, headers,config) { defer.resolve(data); //聲明執行成功 console.log('UserInfoService success'); }) .error(function(data, status, headers, config) { defer.reject(); // 聲明執行失敗 }); return defer.promise; //返回承諾,返回獲取數據的API } } }]); ngApp.contrtoller('MainController', ['$scope','UserInfoService', function($scope, UserInfoService) { var promise = UserInfoService.query(); //同步調用,獲取承諾接口 promise.then(function(data) { $scope.user = data; //調用承諾接口resolve() console.log('MainController..'); }).catch(function(data) { $scope.user = {error: '數據不存在'}; //調用承諾接口reject() }) }])
promise是一種由的方式處理值的方法,是對象,表明了一個函數最終可能的返回值或者拋出的異常。編程
promise可使用鏈式編程json
好比:promise
Service.then(function(data) { // 在這裏必定要用 return 返回 }).then(functon(data) { }).catch(function(data){ })