即使Ember.js模型钩子没有加载所有承诺,如何继续?

我正在加载一条路线.它的模型钩子加载了一些模型.有些是从ember商店获取的,有些是通过
AJAX请求的承诺:

model: function () {
        return Em.RSVP.hash({
            //the server data might not be loaded if user is offline (application runs using appcache, but it's nice to have)
            someServerData: App.DataService.get(),
            users: this.store.find('user')
        });

    }

App.DataService.get()定义为:

get: function () {
    return new Ember.RSVP.Promise(function(resolve, reject) {   
      //ajax request here
    });
}

显然,如果请求被拒绝,流程就会中断,我根本无法显示页面.

有办法克服这个问题吗?

最佳答案
Ember.RSVP.hashSettled正是出于此目的.

来自tildeio / rsvp.js的Github存储库:

hashSettled() work exactly like hash(), except that it fulfill with a hash of the constituent promises’ result states. Each state object will either indicate fulfillment or rejection, and provide the corresponding value or reason. The states will take one of the following formats:

{state:’履行’,价值:价值}
  要么
{state:’拒绝’,理由:原因}

以下是使用它的示例(working JS Bin example):

App.IndexRoute = Ember.Route.extend({
  fallbackValues: {
    firstProperty: null,
    secondProperty: null
  },
  model: function() {
    var fallbackValues = this.get('fallbackValues');
    return new Ember.RSVP.Promise(function(resolve, reject) {
      Ember.RSVP.hashSettled({
        firstProperty: Ember.RSVP.Promise.resolve('Resolved data despite error'),
        secondProperty: (function() {
          var doomedToBeRejected = $.Deferred();
          doomedToBeRejected.reject({
            error: 'some error message'
          });
          return doomedToBeRejected.promise();
        })()
      }).then(function(result) {
        var objectToResolve = {};
        Ember.keys(result).forEach(function(key) {
          objectToResolve[key] = result[key].state === 'fulfilled' ? result[key].value : fallbackValues[key];
        });
        resolve(objectToResolve);
      }).catch(function(error) {
        reject(error);
      });
    });
  }
});

fallbackValues可用于管理已解析的哈希属性的回退值,而不使用promise函数内的条件.

点赞