Node.js Asynchronous Function *Definition*

前端 未结 4 855
失恋的感觉
失恋的感觉 2020-12-30 15:16

Please, just to clear something up in my head...

I am used to writing using asynchronous functions in libraries, but how do I write my own?

To illustrate my

4条回答
  •  长情又很酷
    2020-12-30 15:52

    Actually it sounds a little weird to create a "asynchronous" function without any further description or requirement. Usually, the usage is about avoiding long blocking periods. So if we have a function which triggers a database-query and we want to call another function when this is completed, that function should get called after the job is done and the original function instantely returns the control-flow back to Node (ECMAscript).

    So if we have a construct like

    function someJob( callback ) {
        // heavy work
        callback();
    }
    

    Now, this code still runs very synchronous. To bring that in an async state, we can invoke node's process.nextTick method

    function someJob( callback ) {
        // heavy work
        process.nextTick( callback );
    }
    

    What happens now is, that Node will execute that callback method in a later run through its eventloop (and it does that somewhat intelligent too). Eventho nextTick claims to be much more efficient than setTimeout, its pretty much the same deal (from the ECMAscript coders perspective). So in a browser we could go like

    function someJob( callback ) {
        // heavy work
        setTimeout( callback, 0 );
    }
    

    You would be correct if saying that the above example method doesn't make much sense at all, because the async state happens after the heavy work. Well, true. Infact, you would need to break down the heavy part into smaller peaces and make use of the same idea using .nextTick() to make this really efficient.

    Thats also the reason for my confusion on the beginning, actually every task already offers callback possibilities for you.

提交回复
热议问题