zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[AngularJS] Promise: promise chains, orginaze code

code angularjs Promise
2023-09-14 08:59:21 时间
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;

}