The currentUser variable is out of scope in your example, the .then {} block has its own scope that does not extent to its parent. If you declared your variable above your fetch block it would be available later, but execution will most likely reach your second console.log before the promise is returned as the fetch is an asynchronous process. You have to await the response for the variable to have its contents.
Welcome to the complex world of asynchronous programming! Here are some resources about asynchronous programming https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous
var myId = 12345;
var id;
console.log("Fetching info on " + myId);
fetch("https://exampleapi.org/getjson.php?id=" + myId)
.then(
(successResponse) => {
if (successResponse.status != 200) {
console.log("failed to get a 200 response code");
return null;
} else {
return successResponse.json();
}
},
(failResponse) => {
console.log("failed to get a response");
//exit;
return null;
}
)
.then((data) => {
if (data.id && data.id > 0) {
console.log('In Block', data.id);
id=data.id
}
});
console.log('First Try', id);
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function delayedGreeting() {
console.log('Second Try', id);
await sleep(2000);
console.log('Finally!!!', id);
}
delayedGreeting();
console.log('Third try', id);
console.log might then be: (assuming the data has been received 2000ms after request)
"Fetching info on 12345"
"First Try" undefined
"Second Try" undefined
"Third try" undefined
"In Block" 12345
"Finally" 12345
Due to network congestions or something, it is possible "Finally" would also be undefined. Can you have your code follow down the promise chain as that is what these programming constructs are attempting to solve...?