我正试图从Promises的对象返回值,这些值会打印在控制台中,但当我在HTML上显示时,它会显示"反对承诺";代替返回的Value。我的代码是
const priceConversion = async(data) =>{
const url = 'http://www.geoplugin.net/json.gp?'
const response = await fetch (url)
const resJSON = await response.json()
const val = resJSON['geoplugin_currencySymbol'] + Math.round(data * resJSON['geoplugin_currencyConverter'])
return val
}
此处返回的val类型为String。但是一旦从对象调用它,它就给出上面提到的输出,即"0";对象承诺";对象的代码是
let price = {
basic:{
monthly: priceConversion(0),
annual:priceConversion(0)
},
standard:{
monthly:priceConversion(9),
annual:priceConversion(4.5),
},
premium:{
monthly:priceConversion(17),
annual:priceConversion(7)
}
}
对于文档操作,我使用以下方法
let monthly = true
if (monthly === true){
$("#freeMonthly").empty().text(`${price.basic.monthly}`)
$("#standardMonthly").empty().text(`${price.standard.monthly}`)
$("#premiumMonthly").empty().text(`${price.premium.monthly}`)
}
如果有人能帮我解决这个问题,那就太好了,因为我找不到任何解决方案。非常感谢。
尝试将所有内容封装在async
函数中,并在每次调用函数时使用await
:
const priceConversion = async(data) => {
const url = 'http://www.geoplugin.net/json.gp?'
const response = await fetch(url)
const resJSON = await response.json()
const val = resJSON['geoplugin_currencySymbol'] + Math.round(data * resJSON['geoplugin_currencyConverter'])
return val
}
const calculatePrice = async() => {
return {
basic: {
monthly: await priceConversion(0),
annual: await priceConversion(0)
},
standard: {
monthly: await priceConversion(9),
annual: await priceConversion(4.5),
},
premium: {
monthly: await priceConversion(17),
annual: await priceConversion(7)
}
}
}
const main = async() => {
try {
console.log("In the main")
const price = await calculatePrice()
let monthly = true
if (monthly === true) {
$("#freeMonthly").empty().text(`${price.basic.monthly}`)
$("#standardMonthly").empty().text(`${price.standard.monthly}`)
$("#premiumMonthly").empty().text(`${price.premium.monthly}`)
}
} catch (err) {
console.log(err)
}
}
main()
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="freeMonthly">freeMonthly</div>
<div id="standardMonthly">standardMonthly</div>
<div id="premiumMonthly">premiumMonthly</div>
</body>
</html>