拒绝/解决身体外的承诺

时间:2014-06-19 17:40:30

标签: ember.js promise cancellation

我需要拒绝来自机构外部的承诺,以处理想要取消操作的用户的情况。

在这里,我需要通过在每个排队的上传中调用#start来同时启动多个上传。 管理上传队列的类然后存储所有承诺,并使用Ember.RSVP.all来处理所有承诺何时已解决或已拒绝的承诺。这很好。

现在,我想取消上传

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 */)
  }
});

我已经考虑过很多方法来处理它,但我找不到像myPromise.reject(reason)这样的方法。

所以我做的是将reject函数存储在Upload实例中,并使用我的cancel方法调用它,如下所示:

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 */)
  }
});

这听起来有点脏,我想知道是否有更好的方法来制作它。

谢谢你的时间!

1 个答案:

答案 0 :(得分:7)

var deferred = Ember.RSVP.defer();

deferred.resolve("Success!");
deferred.reject("End of the world");

访问承诺(用于等等)

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