I have the following JavaScript code:
async function awaitFetch(urlString) {
try {
let status = await fetch(urlString);
return status;
} catch(e) {
alert(e);
}
}
let response = null;
let url = 'https://stackoverflow.com';
awaitFetch(url).then(function (resolve) { response = resolve.status });
while (response === null) {};
console.log(response);
The while loop runs eternally, and I find that response never changes from null because the promise never resolves. Why does my code behave this way? I expect the loop to stop executing when the asynchronous code turns response into 200 or what have you (something besides null), but that never happens. The loop executes forever, and my console.log() is never run. Why is this?
All that I'm really trying to do is pause execution until response is an actual response, and then log it. I also have the constraint that I can't put the console.log() within the .then(). If the event loop is blocked by my while loop, what is a way that I can pause execution until response updates without putting my console.log() in an async function or a .then()??