简体   繁体   中英

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? 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":

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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