angular.js处理多个异步请求方法

在实际业务中,经常会遇到需要等待几个请求完成后再进行下一步的操作。但是angularjs中不支持同步的请求。

解决方案一:

$http.get('url1').success(function(d1){

         $http.get('url2').success(function(d2){

                         //处理逻辑

          });

});

解决方案二:

then中的方法会按照顺序来执行

var app = angular.module('app',[]);

app.controller('promiseControl',function($scope,$q,$http) {

         function getJson(url){

                var deferred = $q.defer();

                $http.get(url)

                     .success(function(d){

                                d = parseInt(d);

                                console.log(d);

                               deferred.resolve(d);

});

            return deferred.promise;

}

getJson('json1.txt').then(function(){

               return getJson('json2.txt');

}).then(function(){

             return getJson('json1.txt');

}).then(function(){

               return getJson('json2.txt');

}).then(function(d){

               console.log('end');

});

});

解决方案三:

$q

刚接触,不太理解

















app.controller('promiseControl',function($scope,$q,$http) {

function getJson(url){

var deferred = $q.defer();

$http.get(url)

.success(function(d){

d = parseInt(d);

console.log(d);

deferred.resolve(d);

});

return deferred.promise;

}

getJson('json1.txt').then(function(){

return getJson('json2.txt');

}).then(function(){

return getJson('json1.txt');

}).then(function(){

return getJson('json2.txt');

}).then(function(d){

console.log('end');

});

});

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,842评论 2 17
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,981评论 19 139
  • 不支持上传文件,所以就复制过来了。作者信息什么的都没删。对前端基本属于一窍不通,所以没有任何修改,反正用着没问题就...
    全栈在路上阅读 1,999评论 0 2
  • 我们都总喜欢说时代变了 社会变了 别人变了……我们总是习惯将所有的不如意和不顺心都怪到别人的身上 从来不找自己的原...
    Sunshinelwy阅读 324评论 0 0
  • 大家都知道孟母三迀的故事,所以说环境对工作学习有着很大的影响,什么样的环境偶遇什么样的人,环境不同,遇到的人,事,...
    尚源希妈妈阅读 177评论 0 1