I’m having a problem using the belongsTo relationship in my call model file. I want to have the file element in the call model point to a file and be able to access the elements present in the file model. The file element in the call model was originally only the object id for that particular file.
The call model
The file model
The issue I’m having is that I don’t know how to access the content of the file model in the call controller. I understand that call.file on line 9 in the controller is returning a promise, but I don’t know how to deal with this since I’m having to loop through individual calls. If I use something like “call.file.filename” on line 9, it returns as undefined.
Relationships in Ember Data are async by default, so they will return a promise when you reference them. This means that you have to treat them as async when “reading” them, so to use the results of the promise you have to wait until the promise has resolved (even if that’s right away).
When you get an async relationship (e.g. call.file) you may be triggering an async fetch, so you have to behave as if you are always dealing with an async fetch. If the relationship has already been fetched the promise will simply resolve immediately. But either way you still have to deal with the promise. That means a computed property like this will have to return a promise.
If you’re using relationships in a regular function you can make the function async and use async/await syntax:
async function getFileSize() {
let calls = this.model.calls;
let firstCall = calls[0[;
let firstFile = firstCall.file;
// now firstFile is a regular model not a promise because has been resolved with await
return firstFile.size;
}
IIRC you can’t use async/await with getters so you’d have to do it the old-fashioned promise chain way:
async function getFileSize() {
let calls = this.model.calls;
let firstCall = calls[0[;
return firstCall.file.then(file => {
// now firstFile is a regular model not a promise because has been resolved with promise.then
return file.size;
});
}
You can also reference the proxy value of the relationship e.g. file.call.content if you know the relationship has been loaded.
If you know the data will already be loaded every time you can make the relationship synchronous which means you don’t have to deal with promises at all.