I want to know how to extract a value from a website. I send data to thingspeak and the website displays this: {"created_at":"2019-03-10T18:41:02Z","entry_id":190,"field1":"27.34"} I want to extract the value of the field1, the 27.34. I am new to javascript, this is what I did so far:
const fetch = require('node-fetch');
var url = 'the url goes here';
var lastTemp;
fetch(url)
.then(res => res.json())
.then(json => lastTemp = console.log(json.field1));
console.log(lastTemp);
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();
console.log(ans);
Are executed immediately, therefore, before the fetch has finished and the response received.
Javascript is typically executed line by line, but when you want to delay running code until something else has run, this is when you should be writing functions that get called with the details you want.
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 .