Node.js nodejs是异步/同步进程、非阻塞/阻塞IO

Node.js nodejs是异步/同步进程、非阻塞/阻塞IO,node.js,asynchronous,blocking,nonblocking,synchronous,Node.js,Asynchronous,Blocking,Nonblocking,Synchronous,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

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=新对象();
Person.find().exec(函数(err,docs){

for(var i=0;i节点在一个进程上工作,除了能够为某些异步处理转换到本机代码之外。这些通常是i/O调用,如网络和数据库访问


您的
while(new Date().getTime()
将被阻止。但是,请查看您的
产品。find()
调用。您向其传递一个回调函数。从回调函数中运行的代码是异步的,并且会在I/O完成时通知您。

获得此执行顺序的原因是,您显示的唯一异步函数是
Person.find().exec()
Product.find()

您看到的顺序如下:

  • 您的变量实例化是同步的
  • Person.find().exec()
    是异步的,不会阻塞主线程
  • 主线程没有被阻塞,因此
    console.log('Listening on port 3000')
    运行
  • console.log()
    是同步的,因此设置了
    var startTime
  • console.log('wait');
    是同步的,并在执行后继续
  • while()
    循环运行。它阻塞主线程
  • 事件循环继续,运行
    console.log('0');
  • listen()
    console.log('4')
    函数都是同步运行的
  • Person.find().exec()
    最终运行并启动
    for
    循环
  • 循环是也会阻塞。所有迭代都会在继续之前完成
    
  • 由于循环已停止阻塞主线程,因此运行
    console.log('3')
  • 执行循环中异步函数的回调
  • 作为总结,您的程序在
    while()
    循环处停止,因为循环正在阻塞。如果要延迟代码的执行,请使用全局计时器函数之一,在不阻塞主线程的情况下执行此操作:

    setTimeout(function() {
      console.log('0');
    
      app.listen(3000);
      console.log('4');
    }, 5000);
    

    那么,你的意思是,异步处理只发生在具有回调功能的功能上?通常,是的。大多数时候,你不想冻结UI或只是旋转,你想让系统继续处理消息。许多调用都有同步和异步版本,以防你想等待(在
    http://nodejs.org/api/all.html
    。谢谢,但是哪个函数是异步函数(非阻塞),哪个是同步函数(阻塞)?函数
    Person.find().exec()
    ,和
    Product.find()
    是非阻塞的,
    console.log()
    while()
    for()
    listen()
    正在阻塞。
    setTimeout(function() {
      console.log('0');
    
      app.listen(3000);
      console.log('4');
    }, 5000);