[AngularJS] Promise: promise chains, orginaze code
angular.module( "FlightDemo", [ "FlightServices" ] ) .controller( "flightDashboard", FlighDashboard ); (function (angular) { "use strict"; angular.module("filghtServices", []) .service("user", function () { return{ email: "answer881215@gmail.comm", repository: "http://cs.uef.fi/paikka/zhentiw/personal" } }) .service("travelService", function (user, $q) { //Fight API (each returns a promise) return{ getDeparture: function (user) { var defer = $q.defer(); defer.resolve({ userID: user.email, flightID: "UA_21564", date: "01/14/2014 8: 00 AM" }); return defer.promise; }, getFlight: function(flightID){ return $q.resolve({ id: flightID, pilot: "Captain Morgan", plane: { make: "Boeing 717 RC", model: "TA-889" }, status: "onTime" }); } } }) .service("weatherService",function($q){ return{ getForecast: function(date){ return $q.resolve({ date: date, forecast: "rain" }) } } }); }(window.angular));
var FlighDashboard = function($scope, user, travelService, weatherService){ var loadDeparture = function(user){ return travelService .getDeparture(user.email) .then(function(){ $scope.departure = departure; return departure.flightID; }); //return an promise }, loadFlight = function(flightID){ return travelService .getFlight(flightID) .then(function(){ $scope.flight = flight; return flight; }); }, loadForecast = function(){ return weatherService .getForecast($scope.departure.date) .then(function(weather){ $scope.weather = weather; return weather; }); }; loadDeparture(user) .then(loadFlight) .then(loadForecast) .then("ALL finish"); $scope.user = user; $scope.departure = null; $scope.flight = null; $scope.weather = null; }