【问题标题】:How to return values from the Object Promise in Jquery如何从 Jquery 中的 Object Promise 返回值
【发布时间】:2021-08-25 08:54:42
【问题描述】:

我试图从 Promises 的对象返回值,这些值打印在控制台中,但是当我在 HTML 上显示它时,它显示“OBJECT PROMISE”代替返回的值。 我的代码是

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。但是一旦从对象调用它,它就会给出上述输出,即“对象承诺” 对象的代码是

  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 priceConversion(0); 或在其上调用 then 方法:priceConversion(0).then(result => { /*code*/})。我建议您将所有值放入一个数组中并使用Promise.all 将所有转换后的值放入一个数组中,然后您可以将其添加到对象中。
  • 无论何时在代码中调用 priceConversion 函数,您都必须使用 await
  • Uncaught SyntaxError: Unexpected identifier 这是错误,我在对象中调用函数之前放置了等待。
  • 如果你这样做了:await priceConversion(0);,那么这也需要在异步函数中。
  • 正如我在第一条评论中提到的:“一个异步函数总是返回一个承诺” - 你创建了另一个异步函数并将它的返回值分配给“每月”,这是类似的与你以前的一样。您可以在异步函数中移动整个 price 对象,然后等待 priceConversion(...)

标签: javascript jquery async-await es6-promise


【解决方案1】:

尝试将所有内容包装在 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>

【讨论】:

  • 非常感谢,这真的很有帮助
  • 不客气。请注意,这实际上是糟糕的性能,因为使用此代码,您必须等待 API 调用完成才能执行下一个调用。如果您想提高性能(例如,想象一下如果您有更多可能的价格),请查看@Yousaf 评论谈论Promise.all(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
相关资源
最近更新 更多