Node.js: How to programmatically determine asynchronous?

╄→尐↘猪︶ㄣ 提交于 2019-11-29 11:53:19

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).

you can analyze js transformed into an abstract syntax tree with a tool like acorn. you could check to see if function arguments get executed. however, it would be difficult to tell if it was being executed as a callback or for some other purpose. you could also check to see if blocking functions were being called.

i'm not sure if this would get you all the way there but it would be a handy tool to have.

This is not exactly a solution, just a hint on cases which might be indeed a solution.

Many franeworks or libraries, define functions which can work either synchronously or asynchronously, depending on whether the last function argument (the callback) is given.

For example:

function dummy_sync_or_async(data, callback)
{
  if (callback)
  { 
     // call async code
     //..
     callback(result);
  }
  else
  {
    // call sync code
    // ..
    return result;
  } 
}

Then one can check the number of arguments received (for example if working as a proxy to these function methods) and check these against the function signature (i.e function.length)

Then one can decide whether the function is called in sync or async mode.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!