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 the Intel Edison using mraa, and it has native C++ implemented functions like i2c.readReg(address)
that doesn't accept a callback.
- How can I determine if a function is blocking the processor for other system processes?
- How can I determine if other JS can run in the interim?
Or am I not even approaching this the right way?
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:
- a callback function you can pass in
- a returned promise
- some sort of event listener on the object
- some other notification mechanism
- examine the code of the function
- 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.