In reality what happens is that as the variable is populated within callback
, which is asynchronous, when console.log
is reached the variable has not yet been filled.
If you want to run console.log
only after executing the request, you can turn it into a promise and execute only after the request has been resolved.
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');
})();