nodejs中的异步进程是什么?看看我的测试。
+ Person.find(): query on database, it will take time
+ while(): delay for 5s
控制台中的结果如下:
the first: Listening on port 3000
the second: Wait
----third: 0
---------: 4
---------: 2
---------: 2
---------: 3
---------: 1
---------: 1
如果我们说这是异步过程,为什么程序在运行console.log('0')和console.log('4')之前的5s内停止在while()函数?
var Product = mongoose.model('Product', ProductSchema);
var myObject = new Object();
Person.find().exec(function (err, docs) {
for (var i=0;i<docs.length;i++)
{
Product.find({ user: docs[i]._id},function (err, pers) {
myObject[i] = pers;
console.log('1');
});
console.log('2');
}
console.log('3');
});
console.log('Listening on port 3000');
var startTime = new Date().getTime();
console.log('wait');
while (new Date().getTime() < startTime + 5000); //the program stop here for 5s before priting
console.log('0'); //console.log('0') and console.log('4');
app.listen(3000);
console.log('4');