NeilFraser / JS-Interpreter

A sandboxed JavaScript interpreter in JavaScript.
Apache License 2.0
2.01k stars 353 forks source link

detect when the interpreter is waiting for an async function callback #243

Closed FranckFreiburger closed 1 year ago

FranckFreiburger commented 1 year ago

Is it possible to know if the interpreter is idle after a call to myInterpreter.step() (eg. waiting for an async function result) ?

script host:

    interpreter.setProperty(globalObject, 'wait', interpreter.createAsyncFunction(function(timeout, callback) {

        setTimeout(callback, timeout);
    }));

script:

wait(1000)

In this case, I would like to wait for the end of the timeout on the host side instead of calling myInterpreter.step() "for nothing"

FranckFreiburger commented 1 year ago

never mind, I found the myInterpreter.paused_ value.

NeilFraser commented 1 year ago

If you are running JS-Interpreter server-side (and thus are using the uncompiled acorn.js and interpreter.js), then there's no issue.

However, if you are running JS-Interpreter client-side then you'll want to be using the compiled acorn_interpreter.js file. In that case note that .paused_ is a private variable. So the 'compile.sh' script it will randomly renamed it to something shorter (currently it is .ka). Thus you'll need to add a simple getter, export it, then recompile:

Interpreter.prototype.isPaused = function() {
  return this.paused_;
};
Interpreter.prototype['isPaused'] = Interpreter.prototype.isPaused;

If this turns out to be a useful property generally, then I'll add it to the master. But so far you're the first to find a use for it.

FranckFreiburger commented 1 year ago

Thanks for this advice !

I use JS-Interpreter server-side to execute unsafe business logic scripts. As I said in my initial post, my need is to know if the interpreter is waiting for an async function response. If it is the case, I stop calling myInterpreter.step() and I wait for my promise (associated to my async function), and when my promise is resolved, I continue with myInterpreter.step(). Without it, many cycles are wasted doing nothing.

Maybe there is a better way to achieve this ?

NeilFraser commented 1 year ago

Sounds good to me!