我有一个网站使用money.js通过从开放货币交换API获取汇率来进行实时货币转换。JSON数据对象包含一个嵌套的'rates‘对象,然后money.js在回调函数中使用该对象获取data.rates并执行转换。
Money.js还提供了一个包装器,需要在应用程序中设置基本货币和转换速率,并将其存储在其fx.rates对象中。然后由API调用的速率覆盖这些设置。
jQuery实现可以工作,但我想将其转换为普通的js。在回调函数试图将fx.rates映射到data.rates之前,Fetch API似乎工作正常,此时我得到了一个错误: 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对象?任何帮助都是很好的
发布于 2022-10-14 11:57:55
.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的回调:
undefined
console.log的返回值,即console.log第二个then接收前一个then的返回值,即undefined,因此出现错误。
您需要链中的每个then返回要接收的下一个值。
.then(latest => {
console.log(latest);
return latest;
})https://stackoverflow.com/questions/74068694
复制相似问题