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
})
},
最简单的方法是使用 async/await 语法来实现您想要做的事情,这种语法使您的代码更加同步,使其(在我看来)更具可读性。
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);
}
}
它看起来像上面的样子,或者你可以调整它看起来像这样:
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));
}
问题是,您实际上并没有从该承诺中返回任何东西,它需要解决,或者使用另一个承诺返回。
return rate 没有解决这个承诺(尽管它可能应该),而是使用Promise.resolve() 来实现这一点。
因此,尽管 Promise 确实解析了,但返回值并未解析为 .resolve() 未使用。
从 ES6 开始,添加了 async/await 语法,使我们能够编写更同步样式的代码,尽管仍然是异步的,因为它是旧 Promise 语法 (.then/.catch) 的包装。
还有,Object.keys(response.data.rates)有什么用,不能用键名来引用吗?
例如,如果键是“rate1”,您将替换 response.data.rates['rate1']。
我不知道你的用例,所以这只是事后的想法。