2

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;
  });
})
1
  • In asynchronous callbacks, you DON'T use the value outside the callback. You put any code that needs to use the value INSIDE the callback or in a function that you call from the callback. This is because the timing of when the callback is called is completely unknown so the ONLY time you know you can use the value is inside the callback itself when the callback is called. This is how coding for asynchronous operations works in Javascript. Commented Dec 16, 2017 at 3:25

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, but in the second console.log(btcprice) ouside of the http.get, how do make sure that btcprice continues to hold the value?
The second console.log gets executed before the console.log inside the response.on callback. You should create a function which wraps all the code for the btcprice so you can call it when the btcprice is available. Here is an jsfiddle which contains an example: jsfiddle.net/fxageLqr

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.