简体   繁体   中英

EmberJS: promise callbacks when view is destroyed?

I'm having a small issue with promises. I'm sure run loop allows to solve my issue but it's still a bit obscure too me. Problem here: I have a component that do some heavy ajax calls that can take a few seconds to complete. When the promises resolve, I set the data into the componnent so that it can renders a graph from it. The issue is that if in the meantime, user transitions to a new page, the view (and all the components) are destroyed, and when the promises resolve, it tries to set to an object that do not exist yet. And boom, I have an "trying to set on destroyed object error". Here is a small part of the method that is called when the promise resolve:

updateChart: function(timeframe, interval) {
   var self   = this;
   var method = 'get' + this.get('type').capitalize();

   this.set('isLoading', true);

   this.get('slowService')[method](this.get('project')).then(function(result) {
     Ember.run(function() {
       self.set('isLoading', false);
     });

    self.set('data', result);
 });

},

Thanks a lot!

It has been almost 2 years since the question was asked; but a lot has changed since that day. I just wanted to post an answer so that anyone to see the question in future knows that this is not an issue anymore.

There is a wonderful addon that can be used to exactly tackle the kind of questions that is mentioned in this question. ember-concurrency provides writing cancelable promises. Official documentation page explicitly metntions the case summarized in this question as follows:

"ember-concurrency enables you to write Tasks, which are asynchronous, cancelable operations that are bound to the lifetime of the object they live on, which means when the host object is destroyed (eg a component is unrendered), the task is automatically canceled."

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