简体   繁体   English

再次解决已解决的承诺

[英]Resolving the resolved promise again

I'm using $q of AngularJS, when I create a single promise and that promise is already resolved, can it be resolved again? 我使用的是AngularJS的$ q,当我创建一个Promise且该Promise已经解决时,可以再次解决吗? I don't know if this is possible but if not is there a way that I can resolve the same promise again and again. 我不知道这是否可能,但如果没有,我可以一次又一次地解决同样的承诺。 I was thinking of using the notify way but I don't know if there are other ways to do this. 我当时在考虑使用通知方式,但是我不知道是否还有其他方式可以做到这一点。

From Mastering Web Application Development with Angularjs , by Kozlowski and Bacon , Chapter 3 "Communicating with a Back-end Server", section "The Promise API with $q": 摘自Kozlowski和Bacon的精通Angularjs的Web应用程序开发 ,第3章“与后端服务器通信”,“带$ q的Promise API”部分:

A promise that was resolved or rejected once can't change its state. 曾经被解决或拒绝的承诺不能更改其状态。

There is only one chance of providing promised results. 提供承诺结果的机会只有一次。 In other words it is not possible to: 换句话说不可能:

  • Resolve a rejected promise 解决被拒绝的承诺
  • Resolve an already resolved promise with a different result 解决一个已经解决的承诺并产生不同的结果
  • Reject a resolved promise 拒绝达成承诺
  • Reject a rejected promise with a different rejection reason 用不同的拒绝原因拒绝被拒绝的承诺

Those rules are rather intuitive. 这些规则非常直观。 For example, it wouldn't make much sense if we could be called back with the information that there are problems with a pizza order delivery after a pizza was successfully delivered (and probably eaten!). 例如,如果在成功发送(或可能已吃完)比萨之后,可以通过信息告知我们比萨订单发送有问题,回去没有多大意义。

If you provide more code and we can understand better what you are trying to do we might be able to help you. 如果您提供更多代码,并且我们可以更好地了解您要执行的操作,我们可能会为您提供帮助。

what I simply did was reinitialize promise again like so: 我所做的只是再次像这样重新初始化promise:

var appReadyDeferred = $q.defer();
this.prepareAppReadyDeffered = function() {
  appReadyDeferred = $q.defer();
};
this.appReady = function() {
  return appReadyDeferred.promise;
};
this.appResolve = function() {
  appReadyDeferred.resolve();
};
this.appDeferr = function() {
  appReadyDeferred.reject();
};

So I can use 所以我可以用

someService.appReady().then(function() {
   // some code
});

And reinit it using 并使用重新初始化

someService.prepareAppReadyDeffered();

I'm not sure this is the best possible resolution but it seems to work. 我不确定这是否是最佳解决方案,但它似乎可行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM