【问题标题】:How to get variable out of .then如何从.then中获取变量
【发布时间】:2020-08-03 01:29:04
【问题描述】:

我只想从中获取数据:

{"id":"abba5","data":24.555812751177125,"timestamp":1587380298460}

(这是the URL

这是我使用的代码,但它不起作用,我不知道我只想返回数据 (24.555812751177125)。


export class HttpTemperature{
getTemperature(): number{
        Axios.get('http://dummy-sensors.azurewebsites.net/api/sensor/abba5').then (response =>{
            const afgerond = parseFloat(response.data.data).toFixed(0)
            return afgerond
        })
}}

【问题讨论】:

  • 好吧,你不能那么简单地从then 中取出变量,因为http 调用是异步完成的。你能做到的唯一方法是做一个循环阻塞直到你得到答案,但这在性能方面真的很糟糕。这就是promise概念存在的原因,以便您可以将异步操作链接起来。
  • 以及你将如何实现它,因为我不知道它是如何工作的
  • 如何实现这样的循环?在执行Axios.get 之前,您将声明let afgerond。然后,在Axios.get 之后(不在then 内部函数内),你会有一个什么都不做的while 循环,像这样:while(afgerond === undefined) { } 然后返回afgerond。但请不要这样做。按照 diouze 说的做,并修复你的其余代码,以便它可以正常工作。

标签: typescript api axios


【解决方案1】:

只需根据您的要求添加return。顺便说一句,您的函数是异步的,toFixed 函数返回 string,因此它不返回 number,而是返回 Promise,它返回 string,也就是 Promise<string>。如果您希望您的函数返回 Promise<number>,则必须删除 toFixed(0)

export class HttpTemperature{
  getTemperature(): Promise<string> {
    return Axios.get('http://dummy-sensors.azurewebsites.net/api/sensor/abba5').then (response =>{
        const afgerond = parseFloat(response.data.data).toFixed(0)
        return afgerond
    })
}}

你也可以像这样使用 async/await:

export class HttpTemperature{
  async getTemperature(): Promise<string> {
    const response = await Axios.get('http://dummy-sensors.azurewebsites.net/api/sensor/abba5')
    const afgerond = parseFloat(response.data.data).toFixed(0)
    return afgerond
}}

编辑:

此函数是异步的,因此要获取您的温度,您必须调用 await this.getTemperature()this.getTemperature().then(temperature =&gt; ...

像这样的

 async jsonobjecttemperatuur(){
    const httptemperature = new HttpTemperature()
    const t = await httptemperature.getTemperature()
    ...

【讨论】:

  • 感谢您寻找它,但是当我尝试运行它时,我只是不使用我的其他代码
猜你喜欢
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2016-04-25
  • 2017-04-22
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 2011-02-13
相关资源
最近更新 更多