AngularJS 如何仅在承诺解决后才执行代码? (与 Restangular)

AngularJS how do I execute code only after a promise is resolved? (with Restangular)

这可能是一个菜鸟问题,但我仍然无法理解 promises,尤其是如何使用它们编写代码。 (我读过几篇文章,但大多数都是抽象的,我只是写得不够清楚) 我有一个 AngujlarJS 应用程序,它通过 http 请求获取数据到另一个服务器,该服务器首先发送承诺。我已经能够从承诺中检索响应并在我的应用程序中使用它。但是因为我的代码写得不好。它在 promise 解决导致问题之前执行其他代码。它在拥有数据之前开始加载页面。

我有的是:

var userTotals = *http request which returns a promise

$scope.data = userTotals.$object

//code that does someting with $scope.data

我需要的是(我认为)

var userTotals = *http request which returns a promise

$scope.data = userTotals.$object.
  beforethisresolves(function{ 
     show fancy loading icon or something })
  .whenthis resolves(function{
    //code that does someting with $scope.data
  }

但是我无法获得正确的语法。

大体上是这样的:

var promise = $http.post('/url');

console.log('Request started');

promise.then(function(result) {
  console.log('Success');
  console.log(result);
}, function() {
  console.log('Failure');
});

事实上,$q AngularJS documentation 帮助我理解了 promises 概念。

希望对您有所帮助!

var successCallback = function(){//...};
var errorCallback = function(){//...};

$http
 .post('url', data)
 .success(successCallback)
 .error(errorCallback);

//OR

$http
 .post('url', data)
 .then(successCallback, errorCallback);

假设您使用的是 Bootstrap 模式,您可以执行以下操作:

function openModalWithProgressIndicator(deferred) {
  const progressModal = $uibModal.open({
    templateUrl: 'templates/modals/progress.html',
    backdrop: 'static'
  });
  return deferred.then(function (value) {
    return value;
  }).finally(function () {
    progressModal.close();
  });
}

传递给此函数的 deferred 参数是一个承诺。也就是说,您现在可以执行以下操作:

const deferred = $http.post('http://somewhere/data', {foo: 'bar'});

openModalWithProgressIndicator(deferred)
  .then(function (httpResponse) {
    // do sth with httpResponse.data
  }).catch(function (error) {
    // do sth with error
  });

所以要注意的要点是始终执行的 finally 回调。