how do i create a non-blocking asynchronous function in node.js?

前端 未结 10 890
悲&欢浪女
悲&欢浪女 2020-12-02 13:27

How do I create a non-blocking asynchronous function? Below is what I\'m trying to achieve but my program is still blocking...

var sys = require(\"sys\");

f         


        
相关标签:
10条回答
  • 2020-12-02 14:02

    Try to answer this question based on the event loop model (the core of node.js).

    setTimeout(doSomething,0). Yes, setTimeout will add a task into the task queue. And after 0 second, the time is up. Event loop checks the task queues and finds the task is done, and its callback function doSomething is ready to run.

    The above process is async.

    One thing needs to note here is: the callback function doSomething runs on the main thread(or the single thread) of node.js, and the event loop is also running on this thread. Without a doubt, the while(true) loop totally block the thread.

    0 讨论(0)
  • 2020-12-02 14:08

    You can do this without using a child process using nextTick()

    I was just reading this explanation the other day about nextTick... it's a great read IMO

    ---edit: old link is dead. Found a new one right on StackOverflow

    understanding the node.js event queue and process.nextTick

    0 讨论(0)
  • 2020-12-02 14:09

    setTimeout will not create a new thread, so the browser will still hang at the infinite loop.

    You need to rethink your program structure.

    0 讨论(0)
  • 2020-12-02 14:10

    If i do understand what you're after, you have two functions (both take a callback as argument):

    process.nextTick: this function can be stacked, meaning that if it is called recursively, it will loop a huge (process.maxTickDepth) number of times per tick of the event loop.

    or

    setImmediate: this function is much closer to setting a 0 timeout (but happens before).

    In most cases, you should prefer setImmediate.

    0 讨论(0)
  • 2020-12-02 14:10

    This line:

    while(true);
    

    isn't "blocking", it's just busy, forever.

    0 讨论(0)
  • 2020-12-02 14:11

    You can only do asynchronous IO in node.js by using asynchronous IO functions provided by node.js runtime or node.js extensions written in C++. Your own Javascript code is always synchronous in node.js. Asynchronous non-IO code is rarely needed, and node.js designers decided to avoid it at all.

    There are some arcane ways of running Javascript asynchronously in node.js, mentioned by other commenters, but node.js is not designed for this type of work. Use Erlang if you need that type of concurrency, node.js is only about paralell IO, and for parallel computations it is just as bad as Python or PHP.

    0 讨论(0)
提交回复
热议问题