The reason you're getting this order of execution is because the only asynchronous functions you're showing are Person.find().exec()
and Product.find()
.
The order you're seeing is this:
- Your variable instantiation is synchronous.
Person.find().exec()
is asynchronous and doesn't block the main thread.- The main thread isn't blocked, so
console.log('Listening on port 3000')
runs. console.log()
is synchronous, sovar startTime
is set.console.log('wait');
is synchronous and continues after execution.- The
while()
loop runs. It blocks the main thread. - The event loop resumes, running
console.log('0');
. - The
listen()
andconsole.log('4')
functions are both synchronously run. - The
Person.find().exec()
finally runs and starts thefor
loop. - The
for
loop is also blocks. All iterations complete before continuing. - Since the loop has stopped blocking the main thread,
console.log('3')
is run. - The callbacks of the asynchronous functions within the loop execute.
As a summary, your program stops at the while()
loop because the loop is blocking. If you want to delay execution of code, do so without blocking the main thread by using one of the global timer functions:
setTimeout(function() {
console.log('0');
app.listen(3000);
console.log('4');
}, 5000);