I'm struggling to retrieve a string value from a Promise after using .then on a fetch call.
The scenario involves accessing a public API and extracting the rates property from the JSON response.
{
"base": "EUR",
"rates": {
"CAD": 1.4867
},
"date": "2021-03-16"
}
There's a private method in play that triggers fetch on this endpoint and returns a Promise type.
private getCadCurrency(): Promise<Currency> {
return fetch('https://api.ratesapi.io/api/latest?symbols=CAD')
.then(response => response.json())
.then(res => {
return res as Currency
});
}
This is what the Currency interface looks like:
interface Currency {
base: string,
rates: string,
date: string
}
Despite chaining a .then call after calling getCadCurrency(), I continue to receive a Promise object instead of the desired Rate value.
let test = this.getCadCurrency().then(x => { return x.rates });
console.log(test);
A closer look at 'test' through Developer Tools reveals a mixed state - likely representing its initial pending status and then the final outcome.
https://i.sstatic.net/bV9OV.png
How can I successfully extract the rates string?