AsyncKiteJs

An engine that lives on one thread, so suspending code can use it from anywhere.

The engine underneath is single-threaded, as JavaScript is, and the thread that opened it holds it. Every call here hops onto that thread, one at a time, so two callers never overlap.

The values that come back are the engine's own. A number, a string, a boolean, a BigInt, null or undefined is a copy and can be read anywhere. An object, an array or a function still belongs to the engine, so read it inside onEngine; touched from another thread it throws JsEngineError rather than running script there.

val js = asyncKiteJs(Rhino)
js.use { println(js.evaluate("1 + 1").asDouble()) }
js.close()

Functions

Link copied to clipboard
suspend fun await(value: JsValue): JsValue

Waits for value as await does in a script. A promise comes back as what it fulfils with, and a rejection as the JsError it carries. Any other thenable is resolved the way a promise resolves it, so a thenable that answers with a promise comes back as that promise's value. A value that is not thenable comes straight back.

Link copied to clipboard
open override fun close()

Releases the engine. The release runs on the engine's thread, after any call still running there, so it can happen after this returns. A thread made for the engine then ends.

Link copied to clipboard
suspend fun compile(source: String, fileName: String = "<script>"): JsScript

Parses source once, for running more than once.

Link copied to clipboard
suspend fun <T> deferredToPromise(deferred: Deferred<T>, scope: CoroutineScope): JsObject

Hands the script a promise that settles when deferred does. If deferred fails, or is cancelled, or scope is cancelled before it is awaited, the promise rejects with the failure's message.

Link copied to clipboard
suspend fun evaluate(source: String, fileName: String = "<eval>"): JsValue

Parses and runs source on the engine's dispatcher.

Link copied to clipboard
suspend fun evaluateAwaiting(source: String, fileName: String = "<eval>"): JsValue

Runs source and, if it answers a promise, waits for that promise to settle.

Link copied to clipboard
suspend fun <T> onEngine(block: (KiteJs) -> T): T

Runs block on the engine's dispatcher with the engine in hand.

Link copied to clipboard
suspend fun suspendFunction(target: JsObject, name: String, arity: Int = 0, scope: CoroutineScope, body: suspend (List<JsValue>) -> Any?): JsFunction

Binds a host function that suspends. The script sees a normal function returning a promise; body runs on scope and settles it. A body that throws, or is cancelled with scope before or while it runs, rejects the promise with the failure's message.