John Fisher
John Fisher

Reputation: 463

Storing variable value with http.get in NodeJS?

I am having trouble assigning the value to btcprice, when I try to log the variable after the http.get it outputs undefined. I understand that http.get is occurring asynchronously, but don't know what to do in order to fix this. Any help would be great! Thank you.

const http = require('http');
var btcprice;
// request api
http.get(
{
host: 'api.coindesk.com',
path: '/v1/bpi/currentprice.json'
},
function(response){
  // get data
  let body = '';
  response.on('data', function(d) { body += d; });
  response.on('end', function() {
  // manipulate received data
  let parsed = JSON.parse(body);
  btcprice = parsed.bpi.USD.rate;
  });
})

Upvotes: 2

Views: 1501

Answers (1)

Siggy
Siggy

Reputation: 334

I've created an example based on your explanation. You can see that the btcprice is only reassigned when the response is fully received before that the btcprice will have the default value undefined.

const http = require('http');
let btcprice;

// request api
http.get({
  host: 'api.coindesk.com',
  path: '/v1/bpi/currentprice.json'
}, (response) => {
  // get data
  let body = '';
  response.on('data', function(d) {
    body += d;
  });
  response.on('end', function() {
    // manipulate received data
    let parsed = JSON.parse(body);
    btcprice = parsed.bpi.USD.rate;
    console.log(btcprice); // btcprice will now have an value
  });
})

console.log(btcprice); // btcprice will be "undefined" since the response isn't already available

Upvotes: 1

Related Questions