Synchronous vs. Asynchronous

Asynchronous processing is new to version 1.0

Node owes its performance to being able to process asynchronously and though in previous versions of node-julia, all calls were synchronous, with 1.0.0, this is no longer the case. Advantageous yes, however, programs written against the old version using the form that is now asynchronous will break. Keep the following in mind when considering asynchronous versus synchronous usage.

The last argument determines if the call is synchronous or asynchronous

If the last argument to eval or exec is a function, then the call will be done asynchronously and the last argument will be treated as a function callback

The synchronous form.

In this form, eval takes a single argument, which is a string, while exec expects the function name followed by any number of arguments, the last of which is not a function. If there are multiple return values, res will be an array.

  • res = julia.exec(functionName,arg1,arg2,...,argn);
  • res = julia.eval(string);

The asynchronous form.

In this form, eval takes 2 arguments, the first is a string and the second is a function, while exec expects the function name followed by any number of arguments, followed by a function. In both cases, the function will be called with the error message err as the first argument, which will be falsey if there is no error and an error otherwise. If there are multiple return values (e.g. a tuple), then each result component will be bound to a different variable.

  • julia.exec(functionName,arg1,arg2,...,argn,function(err,res1,res2,...resn){ ... });
  • julia.eval(string,function(err,res1,res2,...resn){ ... });

Error processing

As indicated above, the asynchronous form will invoke the callback with the error message err set to a non null value. In comparison, the synchronous form will throw an exception if an error occurs.

Script considerations

All Script calls are synchronous except for Script.exec which has semantics as described above, so following from the example from the Scripts documentation.

If the script contains the following:

sqrt(args[1])

And invoked by the following:

var julia = require('node-julia');
var script = julia.Script('some_script.jl');               // synchronous

console.log('path: ' + script.getPath());                  // synchronous
console.log('module: ' + script.getModuleName());          // synchronous

script.exec(1000,function(err,res) {                       // asynchronous
   console.log('The sqrt of 1000 is ' + res);
});

console.log('The sqrt of 2000 is ' + script.exec(2000));   // synchronous

setTimeout(function(){ console.log('done.'); },1000);

The following is produced (note how the output of the synchronous call is is produced first even though it is lexically second):

path: some_script.jl
module: njIsoMod0
The sqrt of 2000 is 44.721359549995796
The sqrt of 1000 is 31.622776601683793
done.