簡體   English   中英

EmberJS返回模型之前的處理

[英]EmberJS Processing before returning model

在將其返回到掛鈎之前如何對余燼模型進行處理? 我目前在某條路線中的以下路線

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屬於modelB ,即每個modelA都有一個modelB)。 理想情況下,我想要做的是:

return this.store.find('modelA', where modelA.modelB.id = someValue)

當然,問題在於,由於promise之類的問題,僅返回一個空的list_of_modelAs ,並且模型list_of_modelAs空。

我認為我必須以某種方式構造它以從模型掛鈎中返回承諾,但是我不確定如何。

從模型掛鈎返回承諾

由於我幾乎不了解余燼,所以我只能假設以上就是您要嘗試實現的目標-這將實現

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM