const fetch = require('node-fetch');
var url = 'the url goes here';
.then(res => res.json())
.then(json => lastTemp = console.log(json.field1));
This doesn’t seem to work. the json.field1 does seem to have the value I want, but lastTemp doesn’t. I need this value outside of fetch, but I just don’t know how. Thank you for the help.
You will not be able to access the variable in the manner you are trying to because of the synchronous nature of the code you are writing.
These two lines
ans = outsideFunction();
Are executed immediately, therefore, before the fetch has finished and the response received.
Because the console.log('world') is executed immediately but the console.log('hello') is delayed by 1000ms(1 sec).
To get the code to run in the expected order, you would either move the code that has to run after the delayed code is complete directly into the call back function, or write a function that can be called with the value when you have it.
In your example specifically, fetch is delaying the code until it gets a response from the url, so you have to write a function that will call another function when you have the response. OR, write the code that needs the response directly in line with your callback. No way around it. Nature of the beast .