The reason you are seeing this issue is because your code to define ourserver
actually occurs after your console.log("daten: " + ourserver);
, you can prove this to yourself by logging the date, too:
ourserver = server;
console.log(server, new Date());
...
console.log("daten: " + ourserver,new Date());
You will see the daten
console.log
occurs before your log of server
.
When you call fetch
, it will perform the fetching in the background, and once it has completed, it will call the function provided to then
. This is how asynchronous programming works in JavaScript.
Your code that requires ourserver
to be present should happen in your then
.
Here's your code modified to show how I would go about this:
const ip = "myserverip";
fetch('http://myapi.com/list/servers').then(response => {
return response.json();
}).then(list => {
return list.find(server => server.host === ip);
}).then(ourserver => {
console.log("daten: " + ourserver);
});
If you absolutely must access the value of ourserver
outside of the fetch, this can be achieved one of two ways. One way is to define a callback, and the other way is to wait for the value to be set. Here are both ways:
callback
const ip = "myserverip";
let ourserver = null;
const callback = () => {
console.log(ourserver);
}
fetch('http://myapi.com/list/servers').then(response => {
return response.json();
}).then(list => {
ourserver = list.find(server => server.host === ip);
callback();
});
wait
const ip = "myserverip";
let ourserver = null;
fetch('http://myapi.com/list/servers').then(response => {
return response.json();
}).then(list => {
ourserver = list.find(server => server.host === ip);
});
const check = () => {
if(ourserver == null){
return setTimeout(check,100);
}
console.log(ourserver);
};
check();
I do not recommend using the wait and check solution.