在继续之前在 promise 中设置控制器属性

set controller attribute in promise before continue

嗨,我对如何在 Ember 中使用 promises 有疑问。基本上我想在 运行 下一个承诺之前设置我的控制器的属性,我的代码:

export default Ember.Controller.extend({
  min: null,
  max: null,

  isValid: Ember.computed(function(){
    var self = this;

    var result = new Ember.RSVP.Promise(function(resolve, reject){
      var url = "..."
      Ember.$.getJSON(url).then(function(data){
        if (data[0] === 0){
          self.set('errorMessage', "It is a free book");
          return false;
        } else if (data[0] > 2000){
          self.set('errorMessage', "You are poor, go for next");
          return false;
        } else {
          console.log(data); # line 2 of console result
          self.set('min', data[1]);
          self.set('max', data[2]);
          return true;
        }
      });
    });
  }
  return result;
}),

actions: {
    save: function(){
        if (this.get('isValid')){
            console.log('save action is fired. -- VALID' + '--' + this.get('maxPrice')); # line 1 of console result
        } else {
            console.log('save action is fired. -- INVALID');
        }
    }
}           

});

事情在第三个 if 语句中,保存操作中的代码是 运行 在 promise 中设置属性 min 和 max 之前。控制台结果:

> save action is fired. -- VALID--null
> [9, 1, 20]

知道如何在继续操作之前设置值吗?

谢谢,

用另一个承诺包装 jquery 承诺没有多大意义。只需使用 jquery 承诺,return 它,然后由于这是一个异步世界,您需要 then 关闭该承诺。

export default Ember.Controller.extend({
    min: null,
    max: null,

    checkValid: function(url) {
        var self = this;
        return Ember.$.getJSON(url).then(function(data) {
            if (data[0] === 0) {
                self.set('errorMessage', "It is a free book");
                return false;
            } else if (data[0] > 2000) {
                self.set('errorMessage', "You are poor, go for next");
                return false;
            } else {
                console.log(data);#
                line 2 of console result
                self.set('min', data[1]);
                self.set('max', data[2]);
                return true;
            }
        });
    },

    actions: {
        save: function() {
            var self = this;
            var url = ...;
            this.checkValid(url).then(function(result) {
                if (result) {
                    console.log('save action is fired. -- VALID' + '--' + self.get('maxPrice'));
                } else {
                    console.log('save action is fired. -- INVALID');
                }
             });
         }
     }

});

此外,当您使用 RSVP 承诺时,您需要实际调用 resolve/reject 以获得永远解决或拒绝的承诺。这是有关如何使用 RSVP 承诺的快速视频:https://www.youtube.com/watch?v=8WXgm4_V85E