justjake / quickjs-emscripten

Safely execute untrusted Javascript in your Javascript, and execute synchronous code that uses async functions
https://www.npmjs.com/package/quickjs-emscripten
Other
1.27k stars 95 forks source link

wish to add a new api (QuickJSHandle.keepAlive) #140

Closed SuperLiii closed 8 months ago

SuperLiii commented 8 months ago
//just now, I wanted to expand setInterval API like this
const ctx = vm.newContext()
const api = {
    setInterval: (cbk: QuickJSHandle, _delay: QuickJSHandle) => {

        const delay = ctx.getNumber(_delay)
        setInterval(() => {
            if (!cbk.alive) throw new Error("cbk handle is already disposed")
            ctx.callFunction(cbk, ...)

        }, delay)

        //in the end,cbk will be auto disposed
        //maybe i want set some val  to stop auto disposed like cbk.keepAlive=true
        //then I will manually manage when these handles will be released
        //it maybe solve most asynchronous callback problems
        //can this be implemented?or there may be other ways to achieve it?
    }
}

const fn = ctx.newFunction("setInterval", api.setInterval)
ctx.serProp(ctx.global, "setInterval", fn)
fn.dispose();

ctx.evalCode("setInterval(()=>{},1000)")
justjake commented 8 months ago

Hi, this API is already available although it's poorly documented. You can call handle.dup() to clone a handle so that it outlives the function call. I'll update the documentation to call this out.

SuperLiii commented 8 months ago

wow, that's great! Thank you for your support.