通过节点获取动态请求

时间:2019-02-09 18:33:51

标签: javascript node.js npm fetch

我需要从API中获得一个值,该值很快就会实现。问题在于我编写的代码总是带给我相同的价值。我尝试了两种方法:

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

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

您需要了解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);