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
 - Swift
 - Kotlin
 - C++
 
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 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)
  }
}
In C++, a Promise<T> can be created via Nitro's Promise<T> type - for example, to use an asynchronous Thread pool:
std::shared_ptr<Promise<double>> fibonacci(double n) {
  return Promise<double>::async([=]() -> double {
    // This runs on a separate Thread!
    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 {
    try await data.writeToFile("file://tmp/img.png")
  }
}