0

Im learning javascript right now and working on a weather application using node and express. In short, I'm trying to use an api call from open weather map and assign it to a variable so I can access the values simlair to objects. I tried assigning the value to a variable but it doesnt print out the needed data when i try to access it.

var1=request.get(url, (error, response, body) => {
  let json = JSON.parse(body);
  console.log(json);

});

console.log(var1);//doesnt produce the data i need
jasonv94
  • 11
  • 1
  • No. `request.get()` is non-blocking and asynchronous. It returns and continues running the lines of code after it BEFORE it calls its callback. You have to use the `body` value inside the callback itself or call a function and pass it the `body` value from inside the function. This is how asynchronous coding works in node.js. The other structural option is to use `request-promise` instead and use `await` with the returned promise and it will get you more synchronous looking code (though its still asynchronous). – jfriend00 Mar 06 '20 at 00:43
  • You may find it useful to read this [How do I return the response from an asychronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). – jfriend00 Mar 06 '20 at 00:44
  • There must be a few hundred duplicates of a question like this since this is such a common question. I'd suggest do some searching here for "asynchronous", "synchronous", "await", "callback" – jfriend00 Mar 06 '20 at 01:06

1 Answers1

0

You can if request.get returns a Promise:

Example:

const data = await request.get(url, (error, response, body);

Note that this only works if request.get returns a Promise. If it does not, check out some other node libraries for an HttpClient:

https://www.npmjs.com/package/request-promise

mwilson
  • 12,295
  • 7
  • 55
  • 95