Returning a Promise from a Native Module Method
native module async bridging.
the exported method takes resolve and reject as its last parameters; do the async work off the main thread, then settle exactly once with a result or an error.
WHAT THIS TESTS Whether you know the exact bridging contract for returning a Promise from native code and the threading and lifecycle rules.
A GOOD ANSWER COVERS Mark the method as exported to JavaScript and have it return void; the asynchronous result is delivered through callback parameters, not a return value. On Android the method takes a Promise as its last parameter; on iOS the method takes an RCTPromiseResolveBlock and an RCTPromiseRejectBlock as its final two arguments. Perform the actual asynchronous work, such as a network or disk operation, off the main thread using the platform's async mechanism so you do not block UI. When the work completes successfully, call resolve with the result, which must be a bridgeable type such as a number, string, boolean, array, or map. On failure call reject with an error code string, a human-readable message, and optionally the underlying error or throwable so JS gets a meaningful rejection. The contract is that you must settle the promise exactly once: never call both resolve and reject, and never leave it unsettled, which would hang the awaiting JS code.
COMMON WRONG ANSWERS Trying to return the value directly instead of through resolve. Calling both resolve and reject, or forgetting to settle on an error path. Doing blocking synchronous work on the main thread. Resolving with a non-bridgeable type.
LIKELY FOLLOW-UPS Which data types can cross the bridge. The difference between this callback-based approach and a synchronous TurboModule method via JSI. How errors surface as a rejected promise in JS.
ONE CONCRETE EXAMPLE An Android getToken method takes a Promise parameter, launches a background fetch, and on success calls promise.resolve(token); if the fetch fails it calls promise.reject("TOKEN_ERROR", "could not fetch token", e). In JS, await NativeModule.getToken() returns the token or throws with that code and message.
Read the original → react-mongolia.github.io
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.