Class: QuickJSAsyncContext

February 16, 2026 ยท View on GitHub

quickjs-emscripten


quickjs-emscripten / quickjs-emscripten-core / QuickJSAsyncContext

Class: QuickJSAsyncContext

Defined in: packages/quickjs-emscripten-core/src/context-asyncify.ts:30

Asyncified version of QuickJSContext.

Asyncify allows normally synchronous code to wait for asynchronous Promises or callbacks. The asyncified version of QuickJSContext can wait for async host functions as though they were synchronous.

Contents

Extends

Constructors

Constructor

new QuickJSAsyncContext(args): QuickJSAsyncContext

Defined in: packages/quickjs-emscripten-core/src/context.ts:233

Use QuickJSRuntime#newContext or QuickJSWASMModule#newContext to create a new QuickJSContext.

Parameters

args
callbacks

QuickJSModuleCallbacks

ctx

Lifetime<JSContextPointer>

ffi

EitherFFI

module

EitherModule

ownedLifetimes?

Disposable[]

rt

Lifetime<JSRuntimePointer>

runtime

QuickJSRuntime

Returns

QuickJSAsyncContext

Inherited from

QuickJSContext.constructor

Properties

runtime

runtime: QuickJSAsyncRuntime

Defined in: packages/quickjs-emscripten-core/src/context-asyncify.ts:31

The runtime that created this context.

Overrides

QuickJSContext.runtime

Accessors

alive

Get Signature

get alive(): boolean

Defined in: packages/quickjs-emscripten-core/src/context.ts:264

Returns

boolean

true if the object is alive

Inherited from

QuickJSContext.alive


false

Get Signature

get false(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:322

false.

Returns

QuickJSHandle

Inherited from

QuickJSContext.false


global

Get Signature

get global(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:337

global. A handle to the global object inside the interpreter. You can set properties to create global variables.

Returns

QuickJSHandle

Inherited from

QuickJSContext.global


null

Get Signature

get null(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:296

null.

Returns

QuickJSHandle

Inherited from

QuickJSContext.null


true

Get Signature

get true(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:309

true.

Returns

QuickJSHandle

Inherited from

QuickJSContext.true


undefined

Get Signature

get undefined(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:283

undefined.

Returns

QuickJSHandle

Inherited from

QuickJSContext.undefined

Methods

[dispose]()

[dispose](): void

Defined in: packages/quickjs-emscripten-core/src/lifetime.ts:47

Just calls the standard .dispose() method of this class.

Returns

void

Inherited from

QuickJSContext.[dispose]


callFunction()

Call Signature

callFunction(func, thisVal, args?): QuickJSContextResult<QuickJSHandle>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1180

func.call(thisVal, ...args) or func.apply(thisVal, args). Call a JSValue as a function.

See unwrapResult, which will throw if the function returned an error, or return the result handle directly. If evaluation returned a handle containing a promise, use resolvePromise to convert it to a native promise and runtime.QuickJSRuntime#executePendingJobs to finish evaluating the promise.

Parameters
func

QuickJSHandle

thisVal

QuickJSHandle

args?

QuickJSHandle[]

Returns

QuickJSContextResult<QuickJSHandle>

A result. If the function threw synchronously, result.error be a handle to the exception. Otherwise result.value will be a handle to the value.

Example:

using parseIntHandle = context.getProp(global, "parseInt")
using stringHandle = context.newString("42")
using resultHandle = context.callFunction(parseIntHandle, context.undefined, stringHandle).unwrap()
console.log(context.dump(resultHandle)) // 42
Inherited from

QuickJSContext.callFunction

Call Signature

callFunction(func, thisVal, ...args): QuickJSContextResult<QuickJSHandle>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1185

func.call(thisVal, ...args) or func.apply(thisVal, args). Call a JSValue as a function.

See unwrapResult, which will throw if the function returned an error, or return the result handle directly. If evaluation returned a handle containing a promise, use resolvePromise to convert it to a native promise and runtime.QuickJSRuntime#executePendingJobs to finish evaluating the promise.

Parameters
func

QuickJSHandle

thisVal

QuickJSHandle

args

...QuickJSHandle[]

Returns

QuickJSContextResult<QuickJSHandle>

A result. If the function threw synchronously, result.error be a handle to the exception. Otherwise result.value will be a handle to the value.

Example:

using parseIntHandle = context.getProp(global, "parseInt")
using stringHandle = context.newString("42")
using resultHandle = context.callFunction(parseIntHandle, context.undefined, stringHandle).unwrap()
console.log(context.dump(resultHandle)) // 42
Inherited from

QuickJSContext.callFunction


callMethod()

callMethod(thisHandle, key, args?): QuickJSContextResult<QuickJSHandle>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1234

handle[key](...args)

Call a method on a JSValue. This is a convenience method that calls getProp and callFunction.

Parameters

thisHandle

QuickJSHandle

key

QuickJSPropertyKey

args?

QuickJSHandle[] = []

Returns

QuickJSContextResult<QuickJSHandle>

A result. If the function threw synchronously, result.error be a handle to the exception. Otherwise result.value will be a handle to the value.

Inherited from

QuickJSContext.callMethod


decodeBinaryJSON()

decodeBinaryJSON(handle): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:1530

Outputs Handle of the given QuickJS Object in binary form

// imagine receiving data from another via IPC
socket.on("data", chunk => {
 context.newArrayBuffer(chunk)
   ?.consume(handle => context.decodeBinaryJSON(handle))
   ?.consume(handle => console.log(context.dump(handle)))
})

Parameters

handle

QuickJSHandle

Returns

QuickJSHandle

Inherited from

QuickJSContext.decodeBinaryJSON


defineProp()

defineProp(handle, key, descriptor): void

Defined in: packages/quickjs-emscripten-core/src/context.ts:1121

Object.defineProperty(handle, key, descriptor).

Parameters

handle

QuickJSHandle

key

QuickJSPropertyKey

The property may be specified as a JSValue handle, or as a Javascript string or number (which will be converted automatically to a JSValue).

descriptor

VmPropertyDescriptor<QuickJSHandle>

Returns

void

Inherited from

QuickJSContext.defineProp


dispose()

dispose(): void

Defined in: packages/quickjs-emscripten-core/src/context.ts:274

Dispose of this VM's underlying resources.

Returns

void

Throws

Calling this method without disposing of all created handles will result in an error.

Inherited from

QuickJSContext.dispose


dump()

dump(handle): any

Defined in: packages/quickjs-emscripten-core/src/context.ts:1355

Dump a JSValue to Javascript in a best-effort fashion. If the value is a promise, dumps the promise's state. Returns handle.toString() if it cannot be serialized to JSON.

Parameters

handle

QuickJSHandle

Returns

any

Inherited from

QuickJSContext.dump


encodeBinaryJSON()

encodeBinaryJSON(handle): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:1513

Outputs QuickJS Objects in binary form

WARNING: QuickJS's binary JSON doesn't have a standard so expect it to change between version

// imagine sending data to another via IPC
let dataLifetime = context.newString("This is an example")
 ?.consume(handle => context.encodeBinaryJSON(handle))
 ?.consume(handle => context.getArrayBuffer(handle))
socket.write(dataLifetime?.value)

Parameters

handle

QuickJSHandle

Returns

QuickJSHandle

Inherited from

QuickJSContext.encodeBinaryJSON


eq()

eq(handle, other): boolean

Defined in: packages/quickjs-emscripten-core/src/context.ts:932

handle === other - IsStrictlyEqual. See Equality comparisons and sameness.

Parameters

handle

QuickJSHandle

other

QuickJSHandle

Returns

boolean

Inherited from

QuickJSContext.eq


evalCode()

evalCode(code, filename?, options?): QuickJSContextResult<QuickJSHandle>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1277

Like eval(code).

Evaluates code, as though it's in a file named filename, with options options.

  • When options.type is "global", the code is evaluated in the global scope of the QuickJSContext, and the return value is the result of the last expression.
  • When options.type is "module", the code is evaluated is a module scope. It may use import and export if runtime.QuickJSRuntime#setModuleLoader was called. It may use top-level await if supported by the underlying QuickJS library. The return value is the module's exports, or a promise for the module's exports.
  • When options.type is unset, the code is evaluated as a module if it contains an import or export statement, otherwise it is evaluated in the global scope.

When working with async code, you many need to call runtime.QuickJSRuntime#executePendingJobs to execute callbacks pending after synchronous evaluation returns.

See unwrapResult, which will throw if the function returned an error, or return the result handle directly. If evaluation returned a handle containing a promise, use resolvePromise to convert it to a native promise and QuickJSRuntime#executePendingJobs to finish evaluating the promise.

Note: to protect against infinite loops, provide an interrupt handler to QuickJSRuntime#setInterruptHandler. You can use shouldInterruptAfterDeadline to create a time-based deadline.

Parameters

code

string

filename?

string = "eval.js"

options?

If no options are passed, a heuristic will be used to detect if code is an ES module.

See EvalFlags for number semantics.

number | ContextEvalOptions

Returns

QuickJSContextResult<QuickJSHandle>

The last statement's value. If the code threw synchronously, result.error will be a handle to the exception. If execution was interrupted, the error will have name InternalError and message interrupted.

Inherited from

QuickJSContext.evalCode


evalCodeAsync()

evalCodeAsync(code, filename?, options?): Promise<QuickJSContextResult<QuickJSHandle>>

Defined in: packages/quickjs-emscripten-core/src/context-asyncify.ts:44

Asyncified version of evalCode.

Parameters

code

string

filename?

string = "eval.js"

options?

See EvalFlags for number semantics

number | ContextEvalOptions

Returns

Promise<QuickJSContextResult<QuickJSHandle>>


fail()

protected fail(error): DisposableFail<QuickJSHandle>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1539

Parameters

error

QuickJSHandle

Returns

DisposableFail<QuickJSHandle>

Inherited from

QuickJSContext.fail


getArrayBuffer()

getArrayBuffer(handle): Lifetime<Uint8Array<ArrayBufferLike>>

Defined in: packages/quickjs-emscripten-core/src/context.ts:811

Coverts handle to a JavaScript ArrayBuffer

Parameters

handle

QuickJSHandle

Returns

Lifetime<Uint8Array<ArrayBufferLike>>

Inherited from

QuickJSContext.getArrayBuffer


getBigInt()

getBigInt(handle): bigint

Defined in: packages/quickjs-emscripten-core/src/context.ts:802

Converts handle to a Javascript bigint.

Parameters

handle

QuickJSHandle

Returns

bigint

Inherited from

QuickJSContext.getBigInt


getIterator()

getIterator(iterableHandle): QuickJSContextResult<QuickJSIterator>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1081

handle[Symbol.iterator](). See QuickJSIterator. Returns a host iterator that wraps and proxies calls to a guest iterator handle. Each step of the iteration returns a result, either an error or a handle to the next value. Once the iterator is done, the handle is automatically disposed, and the iterator is considered done if the handle is disposed.

for (using entriesHandle of context.getIterator(mapHandle).unwrap()) {
  using keyHandle = context.getProp(entriesHandle, 0)
  using valueHandle = context.getProp(entriesHandle, 1)
  console.log(context.dump(keyHandle), '->', context.dump(valueHandle))
}

Parameters

iterableHandle

QuickJSHandle

Returns

QuickJSContextResult<QuickJSIterator>

Inherited from

QuickJSContext.getIterator


getLength()

getLength(handle): number | undefined

Defined in: packages/quickjs-emscripten-core/src/context.ts:991

handle.length as a host number.

Example use:

const length = context.getLength(arrayHandle) ?? 0
for (let i = 0; i < length; i++) {
  using value = context.getProp(arrayHandle, i)
  console.log(`array[${i}] =`, context.dump(value))
}

Parameters

handle

QuickJSHandle

Returns

number | undefined

a number if the handle has a numeric length property, otherwise undefined.

Inherited from

QuickJSContext.getLength


getNumber()

getNumber(handle): number

Defined in: packages/quickjs-emscripten-core/src/context.ts:773

Converts handle into a Javascript number.

Parameters

handle

QuickJSHandle

Returns

number

NaN on error, otherwise a number.

Inherited from

QuickJSContext.getNumber


getOwnPropertyNames()

getOwnPropertyNames(handle, options?): QuickJSContextResult<DisposableArray<QuickJSHandle>>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1028

Object.getOwnPropertyNames(handle). Similar to the standard semantics, but with extra, non-standard options for:

  • fetching array indexes as numbers (numbers: true)
  • including symbols (symbols: true)
  • only iterating over enumerable properties (onlyEnumerable: true)

The default behavior is to emulate the standard:

context.getOwnPropertyNames(handle, { strings: true, numbersAsStrings: true })

Note when passing an explicit options object, you must set at least one option, and strings are not included unless specified.

Example use:

for (using prop of context.getOwnPropertyNames(objectHandle).unwrap()) {
  using value = context.getProp(handle, prop)
  console.log(context.dump(prop), '->', context.dump(value))
}

Parameters

handle

QuickJSHandle

options?

GetOwnPropertyNamesOptions = ...

Returns

QuickJSContextResult<DisposableArray<QuickJSHandle>>

an an array of handles of the property names. The array itself is disposable for your convenience.

Throws

QuickJSEmptyGetOwnPropertyNames if no options are set.

Inherited from

QuickJSContext.getOwnPropertyNames


getPromiseState()

getPromiseState(handle): JSPromiseState

Defined in: packages/quickjs-emscripten-core/src/context.ts:836

Get the current state of a QuickJS promise, see JSPromiseState for the possible states. This can be used to expect a promise to be fulfilled when combined with unwrapResult:

const promiseHandle = context.evalCode(`Promise.resolve(42)`);
const resultHandle = context.unwrapResult(
 context.getPromiseState(promiseHandle)
);
context.getNumber(resultHandle) === 42; // true
resultHandle.dispose();

Parameters

handle

QuickJSHandle

Returns

JSPromiseState

Inherited from

QuickJSContext.getPromiseState


getProp()

getProp(handle, key): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:961

handle[key]. Get a property from a JSValue.

Parameters

handle

QuickJSHandle

key

QuickJSPropertyKey

The property may be specified as a JSValue handle, or as a Javascript string (which will be converted automatically).

Returns

QuickJSHandle

Inherited from

QuickJSContext.getProp


getString()

getString(handle): string

Defined in: packages/quickjs-emscripten-core/src/context.ts:781

Converts handle to a Javascript string.

Parameters

handle

QuickJSHandle

Returns

string

Inherited from

QuickJSContext.getString


getSymbol()

getSymbol(handle): symbol

Defined in: packages/quickjs-emscripten-core/src/context.ts:790

Converts handle into a Javascript symbol. If the symbol is in the global registry in the guest, it will be created with Symbol.for on the host.

Parameters

handle

QuickJSHandle

Returns

symbol

Inherited from

QuickJSContext.getSymbol


getWellKnownSymbol()

getWellKnownSymbol(name): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:397

Access a well-known symbol that is a property of the global Symbol object, like Symbol.iterator.

Parameters

name

string

Returns

QuickJSHandle

Inherited from

QuickJSContext.getWellKnownSymbol


newArray()

newArray(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:439

[]. Create a new QuickJS array.

Returns

QuickJSHandle

Inherited from

QuickJSContext.newArray


newArrayBuffer()

newArrayBuffer(buffer): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:447

Create a new QuickJS ArrayBuffer.

Parameters

buffer

ArrayBufferLike

Returns

QuickJSHandle

Inherited from

QuickJSContext.newArrayBuffer


newAsyncifiedFunction()

newAsyncifiedFunction(name, fn): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context-asyncify.ts:91

Similar to newFunction. Convert an async host Javascript function into a synchronous QuickJS function value.

Whenever QuickJS calls this function, the VM's stack will be unwound while waiting the async function to complete, and then restored when the returned promise resolves.

Asyncified functions must never call other asyncified functions or import, even indirectly, because the stack cannot be unwound twice.

See Emscripten's docs on Asyncify.

Parameters

name

string

fn

AsyncFunctionImplementation

Returns

QuickJSHandle


newBigInt()

newBigInt(num): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:405

Create a QuickJS bigint value.

Parameters

num

bigint

Returns

QuickJSHandle

Inherited from

QuickJSContext.newBigInt


newConstructorFunction()

Call Signature

newConstructorFunction(fn): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:635

Convert a Javascript function into a QuickJS constructor function. See newFunction for more details.

Parameters
fn

VmFunctionImplementation<QuickJSHandle>

Returns

QuickJSHandle

Inherited from

QuickJSContext.newConstructorFunction

Call Signature

newConstructorFunction(name, fn): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:636

Convert a Javascript function into a QuickJS constructor function. See newFunction for more details.

Parameters
name

string | undefined

fn

VmFunctionImplementation<QuickJSHandle>

Returns

QuickJSHandle

Inherited from

QuickJSContext.newConstructorFunction


newError()

Call Signature

newError(error): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:679

Parameters
error
message

string

name

string

Returns

QuickJSHandle

Inherited from

QuickJSContext.newError

Call Signature

newError(message): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:680

Parameters
message

string

Returns

QuickJSHandle

Inherited from

QuickJSContext.newError

Call Signature

newError(): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:681

Returns

QuickJSHandle

Inherited from

QuickJSContext.newError


newFunction()

Call Signature

newFunction(fn): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:612

Convert a Javascript function into a QuickJS function value. See VmFunctionImplementation for more details.

A VmFunctionImplementation should not free its arguments or its return value. A VmFunctionImplementation should also not retain any references to its return value.

For constructors (functions that will be called with new ...), use newConstructorFunction.

The function argument handles are automatically disposed when the function returns. If you want to retain a handle beyond the end of the function, you can call Lifetime#dup to create a copy of the handle that you own and must dispose manually. For example, you need to use this API and do some extra book keeping to implement setInterval:

// This won't work because `callbackHandle` expires when the function returns,
// so when the interval fires, the callback handle is already disposed.
const WRONG_setIntervalHandle = context.newFunction("setInterval", (callbackHandle, delayHandle) => {
  const delayMs = context.getNumber(delayHandle)
  const intervalId = globalThis.setInterval(() => {
    // ERROR: callbackHandle is already disposed here.
    context.callFunction(callbackHandle)
  }, intervalId)
  return context.newNumber(intervalId)
})

// This works since we dup the callbackHandle.
// We just need to make sure we clean it up manually when the interval is cleared --
// so we need to keep track of those interval IDs, and make sure we clean all
// of them up when we dispose the owning context.

const setIntervalHandle = context.newFunction("setInterval", (callbackHandle, delayHandle) => {
  // Ensure the guest can't overload us by scheduling too many intervals.
  if (QuickJSInterval.INTERVALS.size > 100) {
    throw new Error(`Too many intervals scheduled already`)
  }

  const delayMs = context.getNumber(delayHandle)
  const longLivedCallbackHandle = callbackHandle.dup()
  const intervalId = globalThis.setInterval(() => {
    context.callFunction(longLivedCallbackHandle)
  }, intervalId)
  const disposable = new QuickJSInterval(longLivedCallbackHandle, context, intervalId)
  QuickJSInterval.INTERVALS.set(intervalId, disposable)
  return context.newNumber(intervalId)
})

const clearIntervalHandle = context.newFunction("clearInterval", (intervalIdHandle) => {
  const intervalId = context.getNumber(intervalIdHandle)
  const disposable = QuickJSInterval.INTERVALS.get(intervalId)
  disposable?.dispose()
})

class QuickJSInterval extends UsingDisposable {
  static INTERVALS = new Map<number, QuickJSInterval>()

  static disposeContext(context: QuickJSContext) {
    for (const interval of QuickJSInterval.INTERVALS.values()) {
      if (interval.context === context) {
        interval.dispose()
      }
    }
  }

  constructor(
    public fnHandle: QuickJSHandle,
    public context: QuickJSContext,
    public intervalId: number,
  ) {
    super()
  }

  dispose() {
    globalThis.clearInterval(this.intervalId)
    this.fnHandle.dispose()
    QuickJSInterval.INTERVALS.delete(this.fnHandle.value)
  }

  get alive() {
    return this.fnHandle.alive
  }
}

To implement an async function, create a promise with newPromise, then return the deferred promise handle from deferred.handle from your function implementation:

const deferred = vm.newPromise()
someNativeAsyncFunction().then(deferred.resolve)
return deferred.handle
Parameters
fn

VmFunctionImplementation<QuickJSHandle>

Returns

QuickJSHandle

Inherited from

QuickJSContext.newFunction

Call Signature

newFunction(name, fn): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:613

Convert a Javascript function into a QuickJS function value. See VmFunctionImplementation for more details.

A VmFunctionImplementation should not free its arguments or its return value. A VmFunctionImplementation should also not retain any references to its return value.

For constructors (functions that will be called with new ...), use newConstructorFunction.

The function argument handles are automatically disposed when the function returns. If you want to retain a handle beyond the end of the function, you can call Lifetime#dup to create a copy of the handle that you own and must dispose manually. For example, you need to use this API and do some extra book keeping to implement setInterval:

// This won't work because `callbackHandle` expires when the function returns,
// so when the interval fires, the callback handle is already disposed.
const WRONG_setIntervalHandle = context.newFunction("setInterval", (callbackHandle, delayHandle) => {
  const delayMs = context.getNumber(delayHandle)
  const intervalId = globalThis.setInterval(() => {
    // ERROR: callbackHandle is already disposed here.
    context.callFunction(callbackHandle)
  }, intervalId)
  return context.newNumber(intervalId)
})

// This works since we dup the callbackHandle.
// We just need to make sure we clean it up manually when the interval is cleared --
// so we need to keep track of those interval IDs, and make sure we clean all
// of them up when we dispose the owning context.

const setIntervalHandle = context.newFunction("setInterval", (callbackHandle, delayHandle) => {
  // Ensure the guest can't overload us by scheduling too many intervals.
  if (QuickJSInterval.INTERVALS.size > 100) {
    throw new Error(`Too many intervals scheduled already`)
  }

  const delayMs = context.getNumber(delayHandle)
  const longLivedCallbackHandle = callbackHandle.dup()
  const intervalId = globalThis.setInterval(() => {
    context.callFunction(longLivedCallbackHandle)
  }, intervalId)
  const disposable = new QuickJSInterval(longLivedCallbackHandle, context, intervalId)
  QuickJSInterval.INTERVALS.set(intervalId, disposable)
  return context.newNumber(intervalId)
})

const clearIntervalHandle = context.newFunction("clearInterval", (intervalIdHandle) => {
  const intervalId = context.getNumber(intervalIdHandle)
  const disposable = QuickJSInterval.INTERVALS.get(intervalId)
  disposable?.dispose()
})

class QuickJSInterval extends UsingDisposable {
  static INTERVALS = new Map<number, QuickJSInterval>()

  static disposeContext(context: QuickJSContext) {
    for (const interval of QuickJSInterval.INTERVALS.values()) {
      if (interval.context === context) {
        interval.dispose()
      }
    }
  }

  constructor(
    public fnHandle: QuickJSHandle,
    public context: QuickJSContext,
    public intervalId: number,
  ) {
    super()
  }

  dispose() {
    globalThis.clearInterval(this.intervalId)
    this.fnHandle.dispose()
    QuickJSInterval.INTERVALS.delete(this.fnHandle.value)
  }

  get alive() {
    return this.fnHandle.alive
  }
}

To implement an async function, create a promise with newPromise, then return the deferred promise handle from deferred.handle from your function implementation:

const deferred = vm.newPromise()
someNativeAsyncFunction().then(deferred.resolve)
return deferred.handle
Parameters
name

string | undefined

fn

VmFunctionImplementation<QuickJSHandle>

Returns

QuickJSHandle

Inherited from

QuickJSContext.newFunction


newFunctionWithOptions()

newFunctionWithOptions(args): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:661

Lower-level API for creating functions. See newFunction for more details on how to use functions.

Parameters

args
fn

VmFunctionImplementation<QuickJSHandle>

isConstructor

boolean

length

number

name

string | undefined

Returns

QuickJSHandle

Inherited from

QuickJSContext.newFunctionWithOptions


newHostRef()

newHostRef<T>(value): HostRef<T>

Defined in: packages/quickjs-emscripten-core/src/context.ts:716

Create an opaque handle object that stores a reference to a host JavaScript object.

The guest cannot access the host object directly, but you may use getHostRef to convert a HostRef handle back into a HostRef from inside a function implementation.

You must call HostRef#dispose or otherwise consume the HostRef#handle to ensure the handle is not leaked.

Type Parameters

T

T extends object

Parameters

value

T

Returns

HostRef<T>

Inherited from

QuickJSContext.newHostRef


newNumber()

newNumber(num): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:356

Converts a Javascript number into a QuickJS value.

Parameters

num

number

Returns

QuickJSHandle

Inherited from

QuickJSContext.newNumber


newObject()

newObject(prototype?): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:425

{}. Create a new QuickJS object.

Parameters

prototype?

QuickJSHandle

Like Object.create.

Returns

QuickJSHandle

Inherited from

QuickJSContext.newObject


newPromise()

Call Signature

newPromise(): QuickJSDeferredPromise

Defined in: packages/quickjs-emscripten-core/src/context.ts:460

Create a new QuickJSDeferredPromise. Use deferred.resolve(handle) and deferred.reject(handle) to fulfill the promise handle available at deferred.handle. Note that you are responsible for calling deferred.dispose() to free the underlying resources; see the documentation on QuickJSDeferredPromise for details.

Returns

QuickJSDeferredPromise

Inherited from

QuickJSContext.newPromise

Call Signature

newPromise(promise): QuickJSDeferredPromise

Defined in: packages/quickjs-emscripten-core/src/context.ts:468

Create a new QuickJSDeferredPromise that resolves when the given native Promise resolves. Rejections will be coerced to a QuickJS error.

You can still resolve/reject the created promise "early" using its methods.

Parameters
promise

Promise<QuickJSHandle>

Returns

QuickJSDeferredPromise

Inherited from

QuickJSContext.newPromise

Call Signature

newPromise(newPromiseFn): QuickJSDeferredPromise

Defined in: packages/quickjs-emscripten-core/src/context.ts:475

Construct a new native Promise, and then convert it into a QuickJSDeferredPromise.

You can still resolve/reject the created promise "early" using its methods.

Parameters
newPromiseFn

PromiseExecutor<QuickJSHandle, Error | QuickJSHandle>

Returns

QuickJSDeferredPromise

Inherited from

QuickJSContext.newPromise


newString()

newString(str): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:363

Create a QuickJS string value.

Parameters

str

string

Returns

QuickJSHandle

Inherited from

QuickJSContext.newString


newSymbolFor()

newSymbolFor(key): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:386

Get a symbol from the global registry for the given key. All symbols created with the same key will be the same value.

Parameters

key

string | symbol

Returns

QuickJSHandle

Inherited from

QuickJSContext.newSymbolFor


newUniqueSymbol()

newUniqueSymbol(description): QuickJSHandle

Defined in: packages/quickjs-emscripten-core/src/context.ts:374

Create a QuickJS symbol value. No two symbols created with this function will be the same value.

Parameters

description

string | symbol

Returns

QuickJSHandle

Inherited from

QuickJSContext.newUniqueSymbol


resolvePromise()

resolvePromise(promiseLikeHandle): Promise<QuickJSContextResult<QuickJSHandle>>

Defined in: packages/quickjs-emscripten-core/src/context.ts:875

Promise.resolve(value). Convert a handle containing a Promise-like value inside the VM into an actual promise on the host.

Parameters

promiseLikeHandle

QuickJSHandle

A handle to a Promise-like value with a .then(onSuccess, onError) method.

Returns

Promise<QuickJSContextResult<QuickJSHandle>>

Remarks

You may need to call runtime.QuickJSRuntime#executePendingJobs to ensure that the promise is resolved.

Inherited from

QuickJSContext.resolvePromise


sameValue()

sameValue(handle, other): boolean

Defined in: packages/quickjs-emscripten-core/src/context.ts:940

Object.is(a, b) See Equality comparisons and sameness.

Parameters

handle

QuickJSHandle

other

QuickJSHandle

Returns

boolean

Inherited from

QuickJSContext.sameValue


sameValueZero()

sameValueZero(handle, other): boolean

Defined in: packages/quickjs-emscripten-core/src/context.ts:948

SameValueZero comparison. See Equality comparisons and sameness.

Parameters

handle

QuickJSHandle

other

QuickJSHandle

Returns

boolean

Inherited from

QuickJSContext.sameValueZero


setProp()

setProp(handle, key, value): void

Defined in: packages/quickjs-emscripten-core/src/context.ts:1106

handle[key] = value. Set a property on a JSValue.

Parameters

handle

QuickJSHandle

key

QuickJSPropertyKey

The property may be specified as a JSValue handle, or as a Javascript string or number (which will be converted automatically to a JSValue).

value

QuickJSHandle

Returns

void

Remarks

Note that the QuickJS authors recommend using defineProp to define new properties.

Inherited from

QuickJSContext.setProp


success()

protected success<S>(value): DisposableSuccess<S>

Defined in: packages/quickjs-emscripten-core/src/context.ts:1535

Type Parameters

S

S

Parameters

value

S

Returns

DisposableSuccess<S>

Inherited from

QuickJSContext.success


throw()

throw(error): JSValuePointer

Defined in: packages/quickjs-emscripten-core/src/context.ts:1314

Experimental

Throw an error in the VM, interrupted whatever current execution is in progress when execution resumes.

Parameters

error

Error | QuickJSHandle

Returns

JSValuePointer

Inherited from

QuickJSContext.throw


toHostRef()

toHostRef<T>(handle): HostRef<T> | undefined

Defined in: packages/quickjs-emscripten-core/src/context.ts:732

If handle is a HostRef<T>.handle, return a new HostRef<T> instance wrapping the handle.

You must call HostRef#dispose or otherwise consume the HostRef#handle to ensure the handle is not leaked.

Type Parameters

T

T extends object

Parameters

handle

QuickJSHandle

Returns

HostRef<T> | undefined

Inherited from

QuickJSContext.toHostRef


typeof()

typeof(handle): string

Defined in: packages/quickjs-emscripten-core/src/context.ts:764

typeof operator. Not standards compliant.

Parameters

handle

QuickJSHandle

Returns

string

Remarks

Does not support BigInt values correctly.

Inherited from

QuickJSContext.typeof


unwrapHostRef()

unwrapHostRef<T>(handle): T

Defined in: packages/quickjs-emscripten-core/src/context.ts:747

If handle is a HostRef<T>.handle, return the host value T.

Type Parameters

T

T extends object

Parameters

handle

QuickJSHandle

Returns

T

Throws

QuickJSHostRefInvalid if handle is not a HostRef<T>.handle

Inherited from

QuickJSContext.unwrapHostRef


unwrapResult()

unwrapResult<T>(result): T

Defined in: packages/quickjs-emscripten-core/src/context.ts:1398

Unwrap a SuccessOrFail result such as a VmCallResult or a ExecutePendingJobsResult, where the fail branch contains a handle to a QuickJS error value. If the result is a success, returns the value. If the result is an error, converts the error to a native object and throws the error.

Type Parameters

T

T

Parameters

result

SuccessOrFail<T, QuickJSHandle>

Returns

T

Inherited from

QuickJSContext.unwrapResult