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:

import { type HybridObject, iOS } from 'nitro-core'

@iOS(...)
export declare class Math extends HybridObject {
fibonacci(n: number): Promise<number>
}

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

The Promise<T> type is built-in in JavaScript.

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) -> any Promise<Void> {
guard let data = image.data else { return }
^ // Error: Cannot return void!
return .async {
try await data.writeToFile("file://tmp/img.png")
}
}

In Swift, Promise<T> is a protocol. Use any Promise<T> in signatures and contextual factories such as .async { ... }, .parallel { ... }, .resolved(with: value), or .rejected(with: error). Nitrogen generates these factories for the promise types used by your specs.