每 3 秒将 console.log 结果存储到数组中

问题描述 投票:0回答:1

我试图每秒仅从币安获取比特币的价格,并将结果存储在数组中。我有以下代码,每次我想要最后的价格时都必须刷新页面。我也不知道如何将其输入到数组中。

var burl ='https://api.binance.com';

var query ='/api/v3/ticker/price';

query += '?symbol=BTCUSDT'; //&interval=15m&limit=2';

var url = burl + query;

var ourRequest = new XMLHttpRequest();

ourRequest.open('GET',url,true);
ourRequest.onload = function(){

  // Will convert the string to something Javascript can understand
  var result = JSON.parse(ourRequest.responseText); 

  // You can now use it as an array
  console.log(result);
}
ourRequest.send();

我还找到了一个 fetch 方法,我不知道如何修改这段代码来帮助我解决这个问题。

componentDidMount() {
    fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
        .then(response => {
            return response.json();
        })
        .then(data => {
            // Here you need to use an temporary array to store NeededInfo only 
            let tmpArray = []
            for (var i = 0; i < data.results.length; i++) {
                tmpArray.push(data.[i])
            }

            this.setState({
                other: tmpArray
            })
        });
} 

非常感谢!!

javascript fetch-api binance
1个回答
0
投票

要每 3 秒发出一次请求,您需要使用 setInterval
要将响应价格推送到数组,您需要使用 array.push(price)

let array = [];
let eachEverySeconds = 3;

function fetchCoinPrice(params) {
  fetch('https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT')
    .then(response => {
        return response.json();
    })
    .then(data => {
        array.push(data.price)
        console.log("tmpArray", array);
    }); 
}

fetchCoinPrice();
setInterval(fetchCoinPrice, eachEverySeconds * 1000);
© www.soinside.com 2019 - 2024. All rights reserved.