Javascript has asynchronous operations. But, a for
loop is synchronous, not asynchronous. The code you show doesn’t use any asynchronous operations, therefore it’s all synchronous.
Should
myfunc()
execute in node and take longer, so that “end” should be invoked earlier because javascript is asynchronous?
No. Nothing in myfunc()
is asynchronous. That’s all synchronous code in your question.
Operations such as setTimeout()
or http.get()
or fs.readFile()
are all asynchronous operations. They don’t change the fact that the for
loop runs synchronously, but the responses to any asynchronous you might put in the loop will happen AFTER your console.log("end")
runs.
If you did something like this:
console.log("start")
myfunc()
console.log("end")
function myfunc(){
for(let i=0; i<10; i++){
setTimeout(function() {
console.log(`timer ${i} done now`);
}, 100);
}
console.log("this should be the end")
}
Would then show this output:
start
this should be the end
end
timer 0 done now
timer 1 done now
timer 2 done now
....
This is the sequence of operations:
- output
console.log("start")
- call myfunc()
- run the
for
loop starting 10setTimeout()
asynchronous operations - finish the
for
loop and outputconsole.log("this should be the end")
myfunc()
returns- Output
console.log("end")
- Some time later the first timer finishes and calls its callback and outputs
timer 0 done now
. - The rest of the timers finish
- The
for
loop runs synchronously and starts all the timers and thenmyfunc()
returns.
3
solved Why are functions synchronous in Javascript?