我正在构建一个使用股票代码数组的 React App 界面:通过节点模块从 finnhub 获取数据 > 将返回的数据推送到数组tickerArr
> 将数组设置为状态变量prices
> 渲染数据。我的代码的简化版本如下所示:
import React, {useState, useEffect} from 'react'
const finnhub = require('finnhub')
const api_key = finnhub.ApiClient.instance.authentications['api_key'];
api_key.apiKey = "api_key"
const finnhubClient = new finnhub.DefaultApi()
export function foo(){
const list = ['AMZN', 'META', 'GOOGL']
const tickerArr = []
const [prices, setPrices] = useState([])
async function fetchData() {
for (const ticker of list){
finnhubClient.quote(ticker, async (err: any, data: any, res: any) =>{
tickerArr.push(data)
})
}
setPrices(tickerArr)
}
useEffect(() => {
fetchData()
}, [])
return(
//Code to render goes here//
)
}
我遇到的问题是使用finnhubClient.quote()
以不同速度返回数据的函数推送到tickerArr
. list
这导致数据与数组中的项目无序。所以在这个特定的例子中,for循环中的每个函数调用都可能需要一些时间来响应和推送,所以即使我从这个顺序开始,['AMZN', 'META', 'GOOGL']
我最终也会得到一个不同['META', 'GOOGL', 'AMZN']
的数据顺序。有没有办法让 for 循环在移动到下一个请求之前等待每个请求完成?在之前添加等待finnhubClient.quote
不起作用。