Node.js: How to programmatically determine asynchronous?

前端 未结 3 1243
半阙折子戏
半阙折子戏 2020-12-19 19:06

I\'d like to be able to take a function that doesn\'t take a callback and determine if it will execute asynchronously.

In particular, I\'m working with Node.js on th

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-19 20:01

    You can't really determine asynchronicity programmatically. It should be clear from the API presented because if it's asynchronous, then there pretty much have to be signs of that in the way you use it.

    If a function is asynchronous, then that means that it does not directly return the result from the function call because the function returns before the result is ready. As such, the documentation for the function has to tell you how to obtain the result and if it's asynchronous there has to be another mechanism such as:

    1. a callback function you can pass in
    2. a returned promise
    3. some sort of event listener on the object
    4. some other notification mechanism
    5. examine the code of the function
    6. function naming convention (such as the suffix "Sync" that node.js uses)

    If the function directly returns the result of the function call, then it is synchronous and other Javascript code will not run during that call.


    If a function is not already asynchronous, the only way to turn that into an async operation is to run it in a different thread or process and marshall the value back to the main thread (calling some sort of callback in the main thread when the value is ready).

提交回复
热议问题