Search code examples
javascriptjavanashorn

Cannot call javascript's async functions from nashorn java


I want to call a javascript function like the following from java using nashorn

async function testSample() {    
    for (var i = 0; i < sample.length; i++) {
        await sample[i]();
    }    
}

So it will execute all the functions in the sample variablel. But I am getting the following error

Expected ; but found function
async function testSample()() {
  ^ in <eval> at line number 8 at column number 6

Is there support for async functions on nashorn?

Any work around to solve this?


Solution

  • async is defined in ECMAScript 2017; Nashorn currently only supports ECMAScript 5.1.

    Therefore, you cannot directly call this code from Nashorn. You could try to rewrite it using Promises, or maybe compile it down to ES5 with something like babel.