This question already has answers here:
Understanding the Event Loop
(4 answers)
Closed 1 year ago.
My understanding is that javascript is single-threaded, meaning it will only execute one line at a time.
For the following code, why is 'await' necessary? I think it will still execute fetch before it moves to the next line:
const res = await fetch('http://testurl.com');
Can someone explain the importance of await in single-thread languages?
Thank you
Two types of functions can be 'paused' mid-function,
Async functions
Generator functions
So while you are correct, only 1 line will be executed at a time, await basically tells Javascript:
This function is now paused, and resume this function once this promise resolves.
While the function is paused, other code can run. But the 'only 1 line of code will run'-rule still holds.
Related
This question already has answers here:
How to wrap async function calls into a sync function in Node.js or Javascript?
(9 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
What is the JavaScript version of sleep()?
(91 answers)
Closed 1 year ago.
My function keeps executing indefinitely, although I would have expected it to resume after 10ms. Is there any way I can flush timeouts while I am waiting for the result? Or at least tell JS to execute / resolve other promises before I return my result?
The simple matter is, I NEED the response before I can continue execution. And I can not put my code in an async block whatsoever. I also can not use 'then' since I need to return the raw result. I thought this hack would work, but nope.
As far as my understanding of JS goes, this simply is not possible, but I would love to know.
let test = function () {
let wait = true;
setTimeout(() => {
wait = false
}, 10);
while (wait);
return wait;
}
you can use async/await , to block the flow of the function
example
const mine = async() => {
console.log("start")
await anotherAsyncFunction()
console.log("done")
}
This question already has answers here:
Why doesn't setTimeout(.., 0) execute immediately?
(1 answer)
Is setTimeout a good solution to do async functions with javascript?
(3 answers)
Closed 4 years ago.
I have below code
console.log('one');
setTimeout(function() { console.log('two'); });
console.log('three');
The output of code when I run it is one, three, two
However I felt it should have been one, two, three as I haven't provided the wait time , which will set the wait time to 0 as default, i.e no waiting.
Then what is the reason that the output is one, three, two and not one, two, three.
setTimeout schedules the function for execution. That scheduler doesn't do its thing until after the current thread yields control back to the browser, e.g. after the last logging statement has executed.
This question already has answers here:
How does setTimeout prevent potential stackoverflow
(2 answers)
Why the function called by setTimeout has no callstack limit?
(2 answers)
Closed 5 years ago.
By using javascript recursive setTimeout function, is it risky to get the stackoverflow?
By trying this example you can see in browser console that the stack grows. Why is it so?
var iteration = 0;
function bar() {
iteration++;
console.log("iteration: " + iteration);
console.trace();
if(iteration < 5){
setTimeout(bar, 5000);
}
}
bar();
By using javascript recursive setTimeout function, is it risky to get the stackoverflow?
No. setTimeout registers a handler that will get called by the browser when the timer triggers. By the time that happens, the stack has unwound (if it hadn't, the task that scheduled the timeout wouldn't have ended, and the browser's UI would be locked up waiting for it to end).
By trying this example you can see in browser console that the stack grows.
No, the stack unwinds before the handler is next called. If you're referring to the async "stack" entries that Chrome's devtools show you, those aren't the real stack, and they're a devtools artifact. (Start your timer, watch for two ticks so you see the "async" entry on the second one, then close your console, wait two more ticks, and reopen it; notice that there aren't any "async" entries — at all, not even the one you saw it log before closing the console!)
This question already has answers here:
Callback of an asynchronous function is never called
(1 answer)
setTimeout not working inside infinite loop
(5 answers)
Closed 5 years ago.
Can't explain nodejs behavior. I have code:
while (true) {
setTimeout(() => console.log(1), 0)
}
And this script just hanging...
How come? I've been thinking setTimeout is non-blocking and asynchronous, and nodejs use timers event loop phase for scheduling setTimeout callbacks... but it seems like event loop blocked...
Your while loop is infinite. It will just keep setting timeouts and never exiting the loop. Since JavaScript is single-threaded, the code for the timeouts won't run until the current code is finished, and since the while loop never finishes, the timeouts don't run.
If you want to spam the console with the number 1 using timeouts, which it looks like you are trying to do, you would have to set the next timeout in the current timeout's callback:
function timeoutFunc() {
console.log(1);
setTimeout(timeoutFunc, 0);
}
timeoutFunc();
This question already has an answer here:
How can I write an async method in JavaScript when posting or looping? [closed]
(1 answer)
Closed 9 years ago.
How to run sequence functions in JavaScript:
I've 4 functions like this:
function myfunction()
{
callfunction1();
callfunction2();
}
In callfunction1:
function callfunction1()
{
callfunction3();
}
My problem is in "myfunction" when I call "callfunction1",callfunction1 is run and it call "callfunction3" but when "callfunction3" haven't finish,"callfunction2" is running.Have anyway to wait "callfunction3" finish then "callfunction2" is run ?
JavaScript is single-threaded, callfunction2 will only run after callfunction3 has compeletely finished.
However, if callfunction3 contains some AJAX or other asynchronous operation, then that will always happen after callfunction2 (because of the single-threaded thing, it can't start the asynchronous callback until after the synchronous stuff is done). Anything that relies on the result of an asynchronous function MUST either be in the function itself, or called by said function.