In reality what happens is that as the variable is populated within the callback
, which is asynchronous, when the console.log
the variable has not yet been completed.
If you want to run the console.log
only after the execution of the request, you can turn it into a promise and execute only after the resolution of the same.
const { get } = require('request');
const { promisify } = require('util');
// Transforma o "get" em uma função que retorna uma promessa
const promisedGET = promisify(get);
const visitar = async uri => {
const { statusCode, body } = await promisedGET({ uri });
// Retorna um erro caso o status seja diferente de 200
if (statusCode !== 200) throw new Error(body);
return { body };
}
(async () => {
// Inicia o timer
console.time('Execução');
try {
const { body } = await visitar('https://exrates.me/openapi/v1/public/ticker?currency_pair=eth_usd');
const a = JSON.parse(body);
const b = a[0]['name'];
console.log(b);
} catch (err) {
console.log(err)
}
// Totaliza o tempo de execução
console.timeEnd('Execução');
})();
There is probably some error within the request, if you are using something from Ajax, use browser developer console, this can help you. Take advantage of and turn off the browser cache.
– Luis Alberto Batista