Rejection / resolution of a promise from outside his body

I need to abandon the promise from his body in order to handle the case of the user who wanted to cancel the action.

Here I need to run several downloads at once, calling #start for each download queued. The class that manages the download queue saves all promises and uses Ember.RSVP.all to process when all promises are allowed or one of them is rejected. It works great.

Now I would like to cancel the download

 App.Upload = Ember.Object.extend({ start: function() { var self = this; return new Ember.RSVP.Promise(function(resolve, reject) { self.startUpload() // Async upload with jQuery .then( function(resp) { resolve(resp) }, function(error) { reject(error) } ); }); }, cancel: function() { this.get('currentUpload').cancel() // Works, and cancels the upload // Would like to reject the promise here }, startUpload: function() { return this.set('currentUpload', /* some jqXHR that i build to upload */) } }); 

I thought of many ways to solve it, but did not find a method like myPromise.reject(reason) .

So what I did was save the reject function in the Upload instance and call it from my cancel method, for example:

 App.Upload = Ember.Object.extend({ start: function() { var self = this; return new Ember.RSVP.Promise(function(resolve, reject) { /* Store it here */ self.set('rejectUpload', reject); /* ------------- */ self.startUpload() // Async upload with jQuery .then( function(resp) { resolve(resp) }, function(error) { reject(error) } ); }); }, cancel: function() { this.get('currentUpload').cancel() // Works, and cancels the upload /* Reject the promise here */ var reject; if (reject = this.get('rejectUpload')) reject(); /* ----------------------- */ }, startUpload: function() { return this.set('currentUpload', /* some jqXHR that i build to upload */) } }); 

This sound is a little dirty for me, and I would like to know if there is a better way to do this.

Thank you for your time!

+6
source share
1 answer
 var deferred = Ember.RSVP.defer(); deferred.resolve("Success!"); deferred.reject("End of the world"); 

To access the promise (for the finish, etc.)

 deferred.promise.then(function(){ console.log('all good'); },function(){ console.log('all bad'); }); 
+7
source

Source: https://habr.com/ru/post/971072/


All Articles