Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Really Stuck

Hi guys. Really stuck on this, im tearing my hair out.

const https = require('https');

const url = "https://api.fixer.io/latest";

function currency(base, end) {
  let currencyData;
  https.get(`${url}?base=${base}&symbols=${end}`, (res) => {
    let body = "";
    res.on('data', (data) => {
      body += data.toString();
    });
    res.on('end', () => {
      currencyData = JSON.parse(body);
      console.log(currencyData); //                         <--------THIS
    });
  });
}

currency("GBP", "USD");

I can get the currencyData variable to print what I need to the console but, if I try to assign it outside the function or push the result to an array, it comes up undefined. How do I retrieve thedata from this?

Thanks

Paul

2 Answers

you declared your currencyData variable within the function, making it a local not global variable. Try declaring the variable outside the currency function and see if that alleviates your problems.

Hi Thanks for your reply. Ive tried that and it still comes up undefined. Its so frustrating that it logs the data but its trapped within the callback and i cant access it

hmmm. Do you have example code on how you are trying to access the variable? That may give a clue as to what is going on.

Think I may have solved it by passing it through a function and storing it in an object literal..phew

Thank you so much for your help

Happy coding

Paul