gpt4 book ai didi

javascript - 带 Node 获取的动态请求

转载 作者:搜寻专家 更新时间:2023-11-01 00:49:23 26 4
gpt4 key购买 nike

我需要从一个快速实现的 API 中获取一个值。问题是我写的代码给我带来的值(value)总是一样的。我尝试了两种方法:

var fetch = require("node-fetch");
for(let i=0; i<5; i++){
setTimeout(function(){}, 3000);
fetch('https://api.binance.com/api/v3/avgPrice?symbol=ETHBTC')
.then(res => res.json())
.then(data => {console.log(data.price)});
}

并以同步方式:

var fetch = require("node-fetch");
var request = async () => {
var response = await fetch('https://api.binance.com/api/v3/avgPrice?
symbol=ETHBTC');
var json = await response.json();
console.log(json.price);
}
for(let i=0; i<5; i++) {
setTimeout(function(){request();}, 3000);
}

但我总是得到这样的东西:

0.03244206
0.03244206
0.03244206
0.03244206
0.03244206

有什么建议吗?

最佳答案

您需要了解 setTimeout 不会停止循环的执行...循环将所有超时设置为一个接一个地执行

const fetch = require("node-fetch");
let i = 0, times = 5;
const interval = setInterval(() => {
if (++i < times) clearInterval(interval);
fetch('https://api.binance.com/api/v3/avgPricesymbol=ETHBTC')
.then(res => res.json())
.then(data => {console.log(data.price)});
},3000);

使用异步/等待:

const fetch = require("node-fetch");
let i = 0, times = 5;
const interval = setInterval(async () => {
if (++i < times) clearInterval(interval);
const response = await fetch("https://api.binance.com/api/v3/avgPricesymbol=ETHBTC");
const json = await response.json();
console.log(json);
},3000);

关于javascript - 带 Node 获取的动态请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54609378/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com