2

I need to obtain a value from an API which is actualized quickly. The problem is that the code I wrote bring me always the same value. I tried two ways:

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)});
}

and in a synchronous fashion:

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);
}

but I always obtain something like this:

0.03244206
0.03244206
0.03244206
0.03244206
0.03244206

Any suggestion?

1 Answers1

2

You need to understand that setTimeout doesnt stop the execution of the loop... The loop sets all timeouts to be executed right one after another

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);

Using async/await:

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);
Matei Adriel
  • 94
  • 1
  • 5
  • I understood my mistake with setTimeout() but using the code you suggest, I got that error: – Julio Federico Buonfigli Feb 12 '19 at 14:52
  • (node:1676) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at https://api.binance.com/api/v3/avgPricesymbol=ETHBTC reason: Unexpected token < in JSON at position 0 at E:\proyectosJavaScript\prueba1\node_modules\node-fetch\lib\index.js:241:32 at process._tickCallback (internal/process/next_tick.js:68:7) (node:1676) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function.... – Julio Federico Buonfigli Feb 12 '19 at 14:53
  • Its probably my fault. What error? I can help you fix it – Matei Adriel Feb 12 '19 at 14:53
  • There is a problem with the json data you are expecting. Can you try logging the response and show me the output? – Matei Adriel Feb 12 '19 at 14:55
  • I edited the code a little bit (the second one) please try again using it ans tell me the result – Matei Adriel Feb 12 '19 at 15:00
  • Congrats:) im happy i helped you – Matei Adriel Feb 12 '19 at 15:41