promise with async

方健發表於2015-02-28
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
        <script src="angular.js"> </script>
    </head>
    <body ng-app="app" ng-controller="con">

    </body>
    <script>
        var app=angular.module("app",[]);
        app.controller("con",function($scope,$http,$q){

            function asyncGreet(name) {
                var deferred = $q.defer();

                setTimeout(function() {
                  deferred.resolve('Hello, ' + name + '!');
                    }, 1000);
                    return deferred.promise;
          }

          function getjson () {
              //return $http.get("x.json");
              var url="http://jsonp.nodejitsu.com/?url=http://api.fanfou.com/users/show/wangxing.json"
              return $http.get(url);
          }

          var promise = asyncGreet('Robin Hood');
          promise.then(function(greeting) {
            console.log('Success1: ' + greeting);
            return getjson();
          }).then(function(greeting) {
            console.log('Success2: ' + greeting);
            return asyncGreet('Robin Hood 3');
          }).then(function(greeting) {
            console.log('Success3: ' + greeting);
            //return asyncGreet('Robin Hood 4');
            return getjson();
          }).then(function(greeting) {
            console.log('Success4: ' + greeting);
          });

        })
    </script>
    </html>

相關文章