0Pricing
React Native Academy · 강의

네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기

Promises와 RCTPromiseResolveBlock을 사용하여 네이티브 코드에서 데이터를 반환하고, RCTEventEmitter로 JavaScript에 이벤트를 보내며, JS에서는 NativeEventEmitter로 처리합니다.

네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기은(는) CoddyKit의 무료 React Native Academy 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 React Native Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Native Methods Must Be Async

React Native native module methods run on a native background thread, not the JavaScript thread. Because the two runtimes run independently, native code cannot return a value directly. Instead it must communicate results back to JavaScript through one of three patterns: Callbacks, Promises, or Events. Each pattern suits different use cases based on how many responses you need and when they arrive.

Callbacks: The Original Pattern

Callbacks are JavaScript functions passed as arguments to a native method. The native code stores them and invokes them later. The convention is to pass two callbacks — one for success and one for failure — similar to Node.js error-first callbacks. A callback can only be invoked once; invoking it twice throws a runtime error on the JS side.

// Kotlin
@ReactMethod
fun readFile(
    path: String,
    successCallback: Callback,
    errorCallback: Callback
) {
    try {
        val content = java.io.File(path).readText()
        successCallback.invoke(content)
    } catch (e: Exception) {
        errorCallback.invoke(e.message)
    }
}

// JavaScript
NativeModules.FileModule.readFile(
  '/data/test.txt',
  (content) => console.log(content),
  (error) => console.error(error)
);

Promises: The Modern Approach

Promises are now the preferred pattern for native methods that return a single result. Add Promise as the final parameter in Kotlin or RCTPromiseResolveBlock / RCTPromiseRejectBlock in Swift. React Native automatically wraps the call in a JS Promise, so you can await it or chain .then(). Promises are self-documenting and integrate naturally with async/await in modern JavaScript.

// Kotlin
@ReactMethod
fun fetchUserData(userId: String, promise: Promise) {
    Thread {
        try {
            val data = apiClient.getUser(userId)
            val map = Arguments.createMap()
            map.putString('name', data.name)
            map.putString('email', data.email)
            promise.resolve(map)
        } catch (e: Exception) {
            promise.reject('FETCH_ERROR', e.message, e)
        }
    }.start()
}

// JavaScript
try {
  const user = await NativeModules.UserModule.fetchUserData('123');
  console.log(user.name);
} catch (err) {
  console.error('Failed:', err.message);
}

Promise Rejection Codes and Messages

When rejecting a Promise, provide three pieces of information: an error code string (like 'PERMISSION_DENIED'), a human-readable message, and optionally the native exception object. On the JavaScript side these become properties of the caught Error: err.code, err.message, and err.nativeStackAndroid or err.nativeStackIOS for debugging.

// Kotlin — structured rejection
@ReactMethod
fun openCamera(promise: Promise) {
    val permission = ContextCompat.checkSelfPermission(
        reactApplicationContext,
        Manifest.permission.CAMERA
    )
    if (permission != PackageManager.PERMISSION_GRANTED) {
        promise.reject(
            'PERMISSION_DENIED',
            'Camera permission is not granted. Please enable it in settings.',
            null
        )
        return
    }
    // proceed...
    promise.resolve(true)
}

// JavaScript
try {
  await NativeModules.CameraModule.openCamera();
} catch (err) {
  if (err.code === 'PERMISSION_DENIED') showSettingsPrompt();
}

Events: Push Data from Native to JS

Events are the right tool when native needs to push data to JavaScript multiple times — such as location updates, sensor readings, download progress, or Bluetooth device discovery. Events flow one-way: native emits, JS listens. On Android you use RCTDeviceEventEmitter; on iOS you use RCTEventEmitter methods.

// Kotlin — emit an event
private fun sendEvent(name: String, data: WritableMap) {
    reactApplicationContext
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
        .emit(name, data)
}

// Call this from a background task:
val map = Arguments.createMap()
map.putDouble('progress', 0.75)
map.putString('fileName', 'video.mp4')
sendEvent('downloadProgress', map)

Listening to Events in JavaScript

On the JS side, subscribe to native events using NativeEventEmitter. Pass it the native module object that emits events, then call addListener with the event name and a handler. Always store the subscription reference and call subscription.remove() in a cleanup function (e.g., inside useEffect's return) to prevent memory leaks from stale listeners.

import React, { useEffect, useState } from 'react';
import { NativeModules, NativeEventEmitter } from 'react-native';

const emitter = new NativeEventEmitter(NativeModules.DownloadModule);

export function DownloadScreen() {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    const sub = emitter.addListener('downloadProgress', (event) => {
      setProgress(event.progress);
    });
    return () => sub.remove(); // cleanup
  }, []);

  return <ProgressBar value={progress} />;
}

addListener and removeListeners on iOS

On iOS, any class that extends RCTEventEmitter must implement two boilerplate methods: addListener(_:) and removeListeners(_:). These let the native module know when JS is actively listening so it can avoid emitting events to an empty audience. Failing to implement them causes a warning in development and may throw in newer RN versions.

// Swift
@objc(DownloadModule)
class DownloadModule: RCTEventEmitter {

  override func supportedEvents() -> [String]! {
    return ['downloadProgress', 'downloadComplete', 'downloadError']
  }

  // Required boilerplate
  override func addListener(_ eventName: String!) { }
  override func removeListeners(_ count: Double) { }

  func reportProgress(_ pct: Double, file: String) {
    sendEvent(
      withName: 'downloadProgress',
      body: ['progress': pct, 'fileName': file]
    )
  }
}

WritableArray for List Results

When you need to return an array from native to JavaScript, use WritableArray and Arguments.createArray(). You push items into it with typed methods like pushString, pushInt, and pushMap. Nested structures (maps inside arrays, arrays inside maps) work seamlessly — React Native serializes the entire tree.

// Kotlin
@ReactMethod
fun listBluetoothDevices(promise: Promise) {
    val array = Arguments.createArray()
    val devices = bluetoothAdapter?.bondedDevices ?: emptySet()
    for (device in devices) {
        val map = Arguments.createMap()
        map.putString('name', device.name)
        map.putString('address', device.address)
        array.pushMap(map)
    }
    promise.resolve(array)
}

// JavaScript
const devices = await NativeModules.BleModule.listBluetoothDevices();
devices.forEach(d => console.log(d.name, d.address));

Choosing Between Callbacks, Promises, and Events

Use this decision guide: Callbacks — legacy codebases or when you need exactly two outcomes (success/error) in one shot. Promises — any single async operation that resolves once; pairs perfectly with async/await. Events — when native must push multiple updates over time (streams, sensors, ongoing background tasks). Most new code should prefer Promises for one-time results and Events for streams.

// Decision chart as comments
// One result, awaitable? → Promise
const photo = await NativeModules.Camera.takePhoto();

// Multiple results over time? → Event emitter
const sub = emitter.addListener('locationUpdate', handleLocation);
NativeModules.LocationModule.startWatching();

// Legacy API you must support? → Callback
NativeModules.OldModule.doThing(onSuccess, onError);

Thread Safety for Event Emission

A common bug is emitting events from a background thread without a listener registered yet, causing a crash or silent drop. On Android, guard with a listener count check. On iOS, RCTEventEmitter handles this internally — sending to zero listeners is silently ignored. Always start background work (GPS polling, BLE scanning) only after the JS side has called the start method, not in the module's initializer.

// Kotlin — safe event emit with listener guard
private var listenerCount = 0

@ReactMethod
fun addListener(eventName: String) {
    listenerCount++
}

@ReactMethod
fun removeListeners(count: Int) {
    listenerCount -= count
}

private fun safeSendEvent(name: String, data: WritableMap) {
    if (listenerCount > 0) {
        reactApplicationContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
            .emit(name, data)
    }
}

Testing Native Module Callbacks in Jest

When unit-testing components that use native modules, mock the module in Jest setup. Replace the native module with a Jest mock object that returns resolved Promises or calls callbacks with test data. This lets you test the JS side in isolation without a real device. Place module mocks in __mocks__/react-native.js or a setup file declared in jest.config.js.

// __mocks__/NativeModules.js
jest.mock('react-native', () => ({
  ...jest.requireActual('react-native'),
  NativeModules: {
    CameraModule: {
      takePhoto: jest.fn(() => Promise.resolve('/path/to/photo.jpg')),
      openCamera: jest.fn(() => Promise.resolve(true)),
    },
    DownloadModule: {},
  },
}));

// In your test
it('captures a photo and sets image URI', async () => {
  const { getByTestId } = render(<CameraScreen />);
  fireEvent.press(getByTestId('shutter-btn'));
  await waitFor(() =>
    expect(getByTestId('preview').props.source).toEqual(
      { uri: '/path/to/photo.jpg' }
    )
  );
});

Quick Check

Test your understanding of React Native Mobile Development concepts from this lesson.

Lesson Recap

In this lesson you learned: how to return data from native using Callbacks, Promises, and Events, how to use WritableMap and WritableArray to pass complex data structures, and how to listen to native events safely in React components with useEffect cleanup. You also saw how to mock native modules in Jest for unit testing. Next up we explore Expo Config Plugins.

자주 묻는 질문

“네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기” 강의는 무료인가요?

네 — “네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 React Native Academy 강의 전체를 잠금 해제할 수 있습니다. React Native Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기”에서 뭘 배우나요?

Promises와 RCTPromiseResolveBlock을 사용하여 네이티브 코드에서 데이터를 반환하고, RCTEventEmitter로 JavaScript에 이벤트를 보내며, JS에서는 NativeEventEmitter로 처리합니다. 브라우저에서 직접 실행하는 실습 코드로 React Native Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

React Native Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 React Native Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 React Native Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 React Native Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Kotlin으로 레거시 네이티브 모듈 작성하기
  2. Swift로 레거시 네이티브 모듈 작성하기
  3. JSI를 사용한 Turbo 네이티브 모듈
  4. 네이티브에서 비동기 콜백, 프로미스 및 이벤트 사용하기
← React Native Academy(으)로 돌아가기