【问题标题】:Use Promises simply to control execution order简单地使用 Promises 来控制执行顺序
【发布时间】:2023-03-16 19:02:02
【问题描述】:

我想知道这是否可能,但我有一系列函数,其中 Promise 将是排序和诸如此类的完美解决方案,但是这些函数不依赖于先前 Promise 的数据。我想使用 Promise 来控制执行顺序,但我仍然需要这些函数才能访问范围闭包。

这里有一些关于原因的上下文。在客户端我有一些对象。各种操作导致客户端保存/更新此对象。我们最近遇到了一个竞争条件,其中两个操作非常接近,服务器实际上损坏了数据库中的对象。我认为使用承诺链会很好,因此更新请求将等到没有其他待处理的更新请求。我需要发送到服务器的更新信息显然存在于范围内,因此我需要能够在 pendingRequestPromise 解决时访问它。

我基本上有这样的东西:

scope.$on("UPDATE", function(event, callback){
    $http.post("update", scope.myObj).success(function(updateInfo){
        callback(updateInfo);
    });
};

如果用户足够快地执行正确的操作,我会向服务器发送 2 个对象,这在上周引起了一些问题。

【问题讨论】:

  • 您能否在您的问题中展示您当前的解决方案(导致竞争条件的解决方案)?
  • 我更新了这个问题,发生的事情和我想要做的事情是否有意义?

标签: angularjs asynchronous promise


【解决方案1】:

我建议像这样使用 $q 服务:

//disable all stuff you want to user not to click with ng-disable
$scope.pageLoading=true;

var update1Promise = $http.post("update1", scope.myObj).success(function(updateInfo){
        callback(updateInfo);
    }),
    update2Promise = $http.post("update2", scope.myObj).success(function(updateInfo){
        callback(updateInfo);
    }),
    update3Promise = $http.post("update3", scope.myObj).success(function(updateInfo){
        callback(updateInfo);
    });

$q.all([update1Promise,update2Promise,update3Promise])then(function() {
    $scope.pageLoading=false;
});

【讨论】:

  • 是的,看起来效果很好。我对承诺的工作方式有些困惑,但这解决了。谢谢!
猜你喜欢
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多