如何在钩子中返回之前对ember模型进行处理?我目前在路线中有以下几行内容
model: function (params) {
var list_of_modelAs = [];
this.store.find('modelA').then(function (modelAs) {
modelAs.forEach ( function (modelA) {
modelA.get('modelB').then(function(modelB) {
if (modelB.get('id') == params.modelB_id) {
list_of_modelAs.push(modelA)
}
})
})
});
return list_of_modelAs;
}
当然,modelA和modelB是使用Ember-Data定义的模型。
我实际上是在创建一个模型数组,但首先要过滤它们。我真正要做的只是过滤模型数组,但我无法找到另一种方法,因为modelB
是一个外来模型(modelA
belongsTo modelB
,即每个modelA都有一个modelB)。理想情况下,我想要做的是:
return this.store.find('modelA', where modelA.modelB.id = someValue)
问题是,当然,由于承诺等原因,只返回一个空的list_of_modelAs
并且模型显示为空。
我假设我必须以某种方式构造它以从模型钩子返回一个promise,但我不太确定如何。
答案 0 :(得分:1)
从模型钩子返回一个承诺
由于我几乎不知道余烬,我只能假设以上是你想要实现的目标 - 这将实现那个
model: function (params) {
return this.store.find('modelA') // important you do a return here, to return the promise
.then(function (modelAs) { // modelAs is an array of modelA - we can use map to change this to an array of modelA.get('modelB') promises
return Promise.all(modelAs.map(function (modelA) { // Promise.all resolves when the array of promises resolves, it resolves to an array of results
return modelA.get('modelB').then(function (modelB) { // just do the asynch stuff here, return modelA if the id is OK, otherwise return null which will be filtered out later
if (modelB.get('id') == params.modelB_id) {
return modelA;
}
else {
return null;
}
});
}));
})
.then(
function(data) { // data is an array of values returned from Promise.all - filter out the null values as they are the ones that don't have the correct ModelB id
return data.filter(function(datum) {
return datum !== null;
});
}
);
// the final return value will be a promise of an array of ModelA whose ModelB has the required `id`
}
使用
调用???.model(params)
.then(function(modelAs) {
// NOTE: modelAs is an array of modelA's not promises
});