我有一个使用货币的网站.js通过从开放货币兑换API获取汇率来进行实时货币转换。JSON 数据对象包含一个嵌套的"rates"对象.js然后在回调函数中使用它来获取 data.rates 并执行转换。
Money.js 还提供了一个包装器,该包装器要求在应用程序中设置基础货币和转换率并存储在其 fx.rates 对象中。然后,这些设置将被 API 调用中的速率覆盖。
jQuery实现可以工作,但我想将其转换为普通js。Fetch API 似乎可以工作,直到回调函数尝试将 fx.rates 映射到 data.rates,此时我收到一个错误:TypeError:无法读取未定义的属性(读取"rates")- 这是 data.rates 而不是 fx.rates。以下是两种方法的简化片段:
import money from 'money';
// Jquery Version
(function( $ ) {
// Declare Default Exchange Rates
var fx = require("money");
fx.rates = {
"EUR" : 1.17,
"USD" : 1.39,
"GBP" : 1,
}
// Init Connect To Open Exchange Rates API
function initOpenExAPI(){
// Load exchange rates data via AJAX:
$.getJSON(
// NB: using Open Exchange Rates here, but you can use any source!
'https://openexchangerates.org/api/latest.json?app_id=XXXXXXXX&base=GBP',
function(data) {
// Check money.js has finished loading:
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
var fxSetup = {
rates : data.rates,
base : data.base,
}
}
initEuroConversion();
}
);
}
//Init Money.js conversion
function initEuroConversion() {
$('.js-price').each( function( index, element ){
var value = $(this).data('price');
fx(value).from('GBP').to('EUR');
});
}
//Init First Call To Open Exchange API On Ready
$(document).ready(function () {
initOpenExAPI();
});
}( jQuery ) );
/**
* Vanilla JS Version
*/
// Declare Default Exchange Rates
const fx = require('money');
fx.rates = {
"EUR" : 1.15,
"USD" : 1.12,
"GBP" : 1,
};
fx.base = "GBP";
/**
* Init Connect To Open Exchange Rates API
*/
function initOpenExAPI(){
// fetch rates
fetch('https://openexchangerates.org/api/latest.json?app_id=XXXXXXXX&base=GBP')
.then(response => response.json())
.then(json => console.log(json))
.then(function (data) {
// Check money.js has finished loading:
// This is where it fails
if ( typeof fx !== "undefined" && fx.rates ) {
fx.rates = data.rates;
fx.base = data.base;
} else {
// If not, apply to fxSetup global:
const fxSetup = {
rates : data.rates,
base : data.base,
}
}
// The API call was successful!
//console.log(data); returns object
initEuroConversion();
})
.catch(function (err) {
// There was an error
console.log('Something went wrong.', err);
});
}
// Money.js conversion
function initEuroConversion() {
const subTotal = document.querySelectorAll('.js-price');
subTotal.forEach(el => {
const value = el.getAttribute('data-price');
fx(value).from('GBP').to('EUR');
});
}
试图理解为什么使用 fetch API 的回调函数无法访问 fx 对象?任何帮助都会很棒
>.then(json => console.log(json)) .then(function (data) { // Check money.js has finished loading: // This is where it fails if ( typeof fx !== "undefined" && fx.rates ) { fx.rates = data.rates;
对代码这一部分中第一个then
的回调:
- 接收一个 JavaScript 对象(从某些 JSON 解析而来,但不是 JSON 本身)
- 记录它 返回
console.log
的返回值,该值为undefined
第二个then
接收前一个then
的返回值,该值undefined
,因此您的错误。
您需要链中的每个then
返回您希望下一个接收的值。
.then(latest => {
console.log(latest);
return latest;
})