changkejun / nashorn-async

Simple async support for Nashorn (the Java 8 JavaScript Engine)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

nashorn-async

Build Status

Asynchronous scripting support for Nashorn.

This project adds optional asynchronous scripting support to javascript snippets evaluated with nashorn.

A snippet may call var done = async() to switch to asynchronous mode. In asynchronous mode the overall script execution will not finish until all timers and intervals got cleared or elapsed and the done callback got invoked with (err, result).

Example Code

A simple asynchronous script:

var done = async();

var timer = setTimeout(function() {

  // do work
  done(null, 'WORK DONE!');
}, 100);

A timeout may also be cleared:

clearTimeout(timer);
done();

Scripts may be synchronous, too and simply return a computed value:

function doWork() {
  return 'WORK DONE!';
}

return doWork();

Async Helpers

Inside a script the following async helpers are available:

  • setTimeout
  • clearTimeout
  • setInterval
  • clearInterval

Using the library from Java

Executing scripts with async support from Java:

ScriptRunner execution = new ScriptRunner(script);

try {
  Object result = execution.execute();
} catch (Exception e) {
  // catches both synchronous and
  // asynchronous exceptions
}

Extending the implementation

Simply evaluate the event-loop.js script that adds optional async support in your script prior to evaluating the target script inside a exec(function() { ...actual script... }) block. See ScriptRunner for details.

Compatible Libraries

Using this library the following projects have been reported to work with Nashorn:

LICENSE

MIT

About

Simple async support for Nashorn (the Java 8 JavaScript Engine)


Languages

Language:JavaScript 55.8%Language:Java 44.2%