Use the data of a request in a global variable

1

I have a difficulty that I'm sure is simple for you!

var request = require('request')
var a
var b

request('https://exrates.me/openapi/v1/public/ticker?currency_pair=eth_usd', function (error, response, body) {

    a = JSON.parse(body)
    b = tickerEx1[0]['name']
    console.log(b) // funciona perfeitamente

})

console.log(b) // nao funciona

I can not use variable b outside the request. I've already tried declaring the variable out, using return ... nothing.

    
asked by anonymous 30.09.2018 / 16:17

1 answer

1

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');
})();
    
30.09.2018 / 19:03