DIV CSS 佈局教程網

AngularJS 中協調多個異步請求的三種常見做法
編輯:關於JavaScript     

在實際業務裡,經常會遇到「必須等好幾個請求都返回後,才能進入下一步」的場景。但 AngularJS 的 $http 並不支持同步請求,因此需要借助一些技巧來編排異步流程。下面彙總三種常用方案。

方案一:回調嵌套

最直接的做法就是把第二個請求寫在第一個請求的成功回調裡,形成嵌套:

$http.get('url1').success(function (d1) {
  $http.get('url2').success(function (d2) {
    // 處理邏輯
  });
});

這種寫法簡單直觀,但層次一多就容易陷入「回調地獄」,可讀性變差。

方案二:利用 then 的順序執行

then 中的方法會按順序串行執行,配合 $q 封裝自定義 promise,可以讓多個請求依次觸發:

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 並發等待

$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);
    })
  });
});

關於 $q 的更詳細用法,網上已有不少教程。以上代碼是筆者結合自身理解整理而成,並經過測試驗證,可放心參考。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved