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.
- TypeScript
- C++
- Swift
- Kotlin
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)
In C++, a Promise<T>
is represented as an std::future<T>
. For example, create one with std::async
:
std::future<double> fibonacci(double n) {
return std::async(std::launch::async, [=]() -> double {
// This runs on a separate Thread!
return calculateFibonacciSequence(n);
});
}
In Swift, a Promise<T>
can be created via Nitro's Promise<T>
type - for example, to use Swift's new async/await syntax:
func fibonacci(n: Double) -> Promise<Double> {
return Promise.async {
// This runs on a separate Thread, and can use `await` syntax!
return try await calculateFibonacciSequence(n)
}
}
In Kotlin, a Promise<T>
can be created via Nitro's Promise<T>
type - for example, to use Kotlin's coroutine syntax:
fun fibonacci(n: Double): Promise<Double> {
return Promise.async {
// This runs on a separate Thread, and can use suspending coroutine functions!
return calculateFibonacciSequence(n)
}
}
Additionally, Nitro statically enforces that Promises can never go stale, preventing you from accidentally "forgetting" to resolve or reject a Promise:
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")
}
}