converter (recipe_line) {
axios.get('https://api.exchangeratesapi.io/latest?base=' + recipe_line.currency_buy + '&symbols=' + this.currentLocation.currency)
.then(response => {
let rate = response.data.rates[Object.keys(response.data.rates)[0]]
return rate
})
},
To simplify and improve readability, you can utilize the async/await
syntax in your code. This approach gives a more synchronous feel to asynchronous operations.
async converter(recipe_line) {
try {
const response = await axiox.get(
'https://api.exchangeratesapi.io/latest?base=' +
recipe_line.currency_buy +
'&symbols=' +
this.currentLocation.currency
);
return response.data.rates[Object.keys(response.data.rates)[0]];
} catch (error) {
console.log(error);
}
}
An alternative implementation would be:
converter(recipe_line) {
axios
.get(
'https://api.exchangeratesapi.io/latest?base=' +
recipe_line.currency_buy +
'&symbols=' +
this.currentLocation.currency
)
.then((response) => {
let rate = response.data.rates[Object.keys(response.data.rates)[0]];
Promise.resolve(rate);
})
.catch((err) => Promise.reject(err));
}
The issue in your original code is that the promise isn't resolving properly. You need to use Promise.resolve()
to ensure the return value is resolved within the promise.
With ES6's async/await
syntax, you have a more synchronous way of handling asynchronous tasks, offering an easier-to-read alternative to traditional Promise chaining (.then/.catch
).
Additionally, consider simplifying Object.keys(response.data.rates)
to directly reference the key name for better clarity and efficiency.
For instance, if the key is "rate1", you could use response.data.rates['rate1']
instead.
Depending on your specific requirements, optimizing this part of the code may enhance its functionality.