我试图每秒仅从币安获取比特币的价格,并将结果存储在数组中。我有以下代码,每次我想要最后的价格时都必须刷新页面。我也不知道如何将其输入到数组中。
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
})
});
}
非常感谢!!
要每 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);