Use data from a request in a global variable

Asked

Viewed 201 times

1

I’m having 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 cannot use the variable b out of the request. I’ve tried declaring the variable out, use Return... nothing.

  • 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.

1 answer

1


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.