javascript - 如何声明一个变量并将其分配给美元的当前汇率?
问题描述
我正在尝试编写一个网站,从用户那里获得一个数字输入作为 TRY(土耳其货币)并将其转换为美元。我想用 js 中的 fetch() 来做到这一点。这是我的代码。如果我写 console.log(data.tr.rate) 而不是 rate = data.tr.rate,它会打印出我想要的美元当前汇率,但是当我在下面编写代码时,它会打印“未定义”。
var rate;
const m_currency = fetch('http://www.floatrates.com/daily/usd.json').then(res => res.json()).then(function(data){
rate = data.tr.rate;
});
console.log(rate);
解决方案
The code where you request the rates JSON is a Promise, which is asynchronous code. You should execute all your code inside the then
block, anything you do outside that block, may execute earlier, so the value of the variable cannot be told.
If you want to fetch synchronously to assign to a variable, you may use an async
function and await
the resolution of the Promise, but async
functions are Promises themselves, that you must run as the fetch
function. Here's an example:
async function get_rate() {
var res = await fetch('http://www.floatrates.com/daily/usd.json');
var data = await res.json();
return data.tr.rate;
};
// works
get_rate().then((rate) => { console.log(rate); });
// doesn't work, no error but it's a promise and not a value
console.log(get_rate());
推荐阅读
- c# - 从其他脚本 Unity 访问脚本
- java - 通过处理与 Arduino 通信的问题
- python - 使用 python-markdown-math 渲染降价的问题
- php - PHP; 通过浏览器与 CLI 访问时,cURL 的行为不同
- java - Spring Boot 应用程序无法启动,并出现错误“应用程序需要一个 bean,但找到了 2 个”
- css - 将共享的 sass 变量导入每个 vue 组件是一种好习惯吗?
- r - 你能用 ggplot2 调整单个堆积条形图的宽度吗?
- python - 目标标签中的缺失值
- sas - SAS - 使用另一个数据集的条件修改一个数据集
- php - 难以从数组的 foreach 中的数组中删除记录