Skip to main content

Promises (Promise<T>)

A function can be made asynchronous by returning a Promise to JS. This allows your native code to perform heavy-, long-running tasks in parallel, while the JS thread can continue rendering and performing other business logic.

In TypeScript, a Promise<T> is represented using the built-in Promise<T> type, which can be awaited:

interface Math extends HybridObject {
fibonacci(n: number): Promise<number>
}

const math = // ...
await math.fibonacci(13)

Additionally, Nitro statically enforces that Promises can never go stale, preventing you from accidentally "forgetting" to resolve or reject a Promise:

HybridMath.swift
func saveToFile(image: HybridImage) -> Promise<Void> {
guard let data = image.data else { return }
^ // Error: Cannot return void!
return Promise.async {
data.writeToFile("file://tmp/img.png")
}
}