Skip to content

Latest commit

 

History

History
74 lines (63 loc) · 2.7 KB

File metadata and controls

74 lines (63 loc) · 2.7 KB


import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';

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` is represented using the built-in `Promise` type, which can be awaited:
```ts
interface Math extends HybridObject {
  fibonacci(n: number): Promise<number>
}

const math = // ...
await math.fibonacci(13)
```
In Swift, a `Promise` can be created via Nitro's [`Promise`](https://github.com/mrousavy/nitro/blob/main/packages/react-native-nitro-modules/ios/core/Promise.swift) type - for example, to use Swift's new async/await syntax:
```swift
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` can be created via Nitro's [`Promise`](https://github.com/mrousavy/nitro/blob/main/packages/react-native-nitro-modules/android/src/main/java/com/margelo/nitro/core/Promise.kt) type - for example, to use Kotlin's coroutine syntax:
```kotlin
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` can be created via Nitro's [`Promise`](https://github.com/mrousavy/nitro/blob/main/packages/react-native-nitro-modules/cpp/core/Promise.hpp) type - for example, to use an asynchronous Thread pool:
```cpp
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 }
  // code-error
                                     ^ // Error: Cannot return void!
  return Promise.async {
    try await data.writeToFile("file://tmp/img.png")
  }
}