I am having a bit of a hard time understanding how javascript asynchronous functions work. In my actual use case, the function in question is a 3rd part API call but a simple setTimeout function is a simpler way to reproduce my problem.
I expect the code infinity loop until the set time function is done and then exit the loop and continue the program. In this example I want/expect the output to be "in set timeout: 5", followed by "out of set timeout: 5" but instead it infinitely loops indicating that the setTimeout function never even runs.
I have also tried without the loop and putting await
before setTimeout(function()
but then it prints "out of set timeout: 1" followed by "in set timeout: 5".
TLDR: I want my code to use an asynchronous function in a synchronous fashion.
async function doWork() {
var a = 1
setTimeout(function() {
a = 5
console.log(`in set timeout: ` + a)
}, 1000)
i = 0
while (a == 1) {}
console.log(`\nout of set timeout: ` + a)
}
doWork()