angularjs $q、$http 處理多個非同步請求

來源:互聯網
上載者:User

標籤:內容   var   tool   title   comm   mod   app   ges   htm   

angularjs $q、$http 處理多個非同步請求

在實際業務中經常需要等待幾個請求完成後再進行下一步操作。但angularjs中$http不支援同步的請求。

解決方案一:

$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.all方法第一個參數可以是數組(對象)。在第一參數中內容都執行完後就會執行then中方法。第一個參數的方法的所有傳回值會以數組(對象)的形式傳入。

var app = angular.module(‘app‘,[]);app.controller(‘promiseControl‘,function($scope,$q,$http) {    $q.all({first: $http.get(‘json1.txt‘),second: $http.get(‘json2.txt‘)}).then(function(arr){        console.log(arr);        angular.forEach(arr,function(d){            console.log(d);            console.log(d.data);        })    });});

解決方案四:

var app = angular.module(‘app‘,[]);app.controller(‘directiveControl‘,function($scope,$http,$q){    function getTxt(a) {        var deferred = $q.defer();        $http.get(‘1.json‘)            .success(function (d) {                console.log(a);                deferred.resolve();            })        return deferred.promise;    }    getTxt(1).then(function(){        return getTxt(2);    }).then(function(){        return getTxt(3);    }).then(function(){        return getTxt(4);    }).then(function(){        return getTxt(5);    }).then(function(){        console.log(‘end‘);    });});

$q的詳細使用方法網上的有很多教程。我也是剛接觸。上面的代碼是我按我的理解寫的,經過了測試沒有問題。

angularjs $q、$http 處理多個非同步請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.