首页 > 解决方案 > 如何声明一个变量并将其分配给美元的当前汇率?

问题描述

我正在尝试编写一个网站,从用户那里获得一个数字输入作为 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);

标签: javascriptjsonfetch

解决方案


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());

推荐阅读