Reputation: 61
I have a problem that I know is not very challenging. But for some reason, I am having difficulty coming up with a good solution. I need to fetch data from a URL. The URL itself, however, is fetched from another end-point. So, first I fetch an object containing the URL from the server. Upon getting the URL, I access the fetched URL which finally gives me the data I need. The data contains further URLs which I eventually have to fetch. How do I fetch all these data from model hook of ember route?
model(params) {
let futureData = new Ember.RSVP.Promise((resolve,reject) => {
api.ajaxGet(
`${api.buildV3EnterpriseUrl('reports')}` + '/' + params.report_id
).then(function (successVal) {
resolve(successVal);
}, function (error) {
reject(error);
});
});
futureData.then((success) => {
return
api.xmlRequest('GET',success.aggregationUrls.elements[0].url);
})
return Ember.RSVP.hash({
reportData: futureData
});
}
Upvotes: 1
Views: 964
Reputation: 664538
You only forgot one tiny bit:
reportData = futureData.then(…)
Calling then
upon the futureData
promise doesn't mutate it, it returns a new promise for the result of the callback. You were ignoring that return value.
Then, after also fixing the Promise
constructor antipattern, it looks like this:
model(params) {
const futureData = api.ajaxGet(`${api.buildV3EnterpriseUrl('reports')}/${params.report_id}`);
const futureReportData = futureData.then(success => {
return api.xmlRequest('GET',success.aggregationUrls.elements[0].url);
});
return Ember.RSVP.hash({
reportData: futureReportData
});
}
which could also be shortened to
model(params) {
return api.ajaxGet(api.buildV3EnterpriseUrl('reports') + '/' + params.report_id)
.then(success => api.xmlRequest('GET',success.aggregationUrls.elements[0].url))
.then(reportData => ({reportData}));
}
Upvotes: 1