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)
.
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();
Inside a script the following async helpers are available:
setTimeout
clearTimeout
setInterval
clearInterval
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
}
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.
Using this library the following projects have been reported to work with Nashorn:
MIT