繁体   English   中英

Function 存储 fetch api 调用作为局部变量(不是承诺)

[英]Function to store fetch api call as local variable (not promise)

我正在向数据库发送 api 请求,以便在小部件中接收数据,对数据进行一些处理,然后 plot 并将其呈现到我的 web 页面。 这是在反应 web 应用程序中完成的。

我正在使用 fetch 来获取数据并接收 promise。 获取是在 function 内部完成的,我稍后会调用它多次。 我已经找到了如何在进行 api 调用时直接从 fetch promises 中控制台记录数据的示例,但是在 function 中执行此操作似乎总是导致 promise 没有返回数据的想法!

任何可以提供的帮助将不胜感激。 我当前的代码如下并返回 promise。

谢谢你。

class MyWidget extends Component {
    constructor(props) {
        super(props)
    }

async fetchData(url) {
    try {
        const response = await fetch(url);
        const data = await response.json();
        return data;
    } catch (error) {
        console.error(error);
    }
}

async readDB(url) {
    const data = await this.fetchData(url);
    return data
}

processingFunction() {
    const url = 'my/database/api/variable=X'
    const database_data = this.readDB(url)
    // perform processing on database data...
    // plot processed data...
}

您必须在processingFunctionawait ,也必须将其更改为async

async processingFunction() {                      // change to async
    const url = 'my/database/api/variable=X'
    const database_data = await this.readDB(url); // await the async result
    // perform processing on database data...
    // plot processed data...
}

但似乎你根本不需要readDB func

async processingFunction() {
    const url = 'my/database/api/variable=X'
    const database_data = await this.fetchData(url);

}

更新

您不能将 Promise 转换为 Array 或其他。 React 中有一定的流程:state + 生命周期钩子。 在这种情况下,您必须将数据存储在 state 并使用componentDidMount挂钩

import React, {Component} from 'react'

class MyWidget extends Component {
  state = {
    dataFromDB: null // set initial state
  };

  processingFunction() {
    const yourData = this.state.dataFromDB;
    // perform processing on database data...
    // plot processed data...
  }
  
  async componentDidMount() {
    const url = "my/database/api/variable=X";
    const database_data = await this.fetchData(url);
    
    this.setState(() => ({
      dataFromDB: database_data // set data in state from DB
    }));
  }
  
  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM