Emscripten
JavaScript
C++
Async Programming
WebAssembly

How to handle promise when calling async JS method from C using Emscripten

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

When C or C++ code compiled with Emscripten calls JavaScript APIs that return Promises, you need a bridge between synchronous native control flow and asynchronous browser execution. If the bridge is wrong, native code returns early, memory ownership breaks, or Promise rejections are lost. The reliable solution is Asyncify with explicit async wrappers.

Use EM_ASYNC_JS for Promise-Aware Bridges

EM_ASYNC_JS allows JavaScript await inside functions that look synchronous to native callers.

cpp
1#include <cstdio>
2#include <emscripten.h>
3
4EM_ASYNC_JS(int, fetch_number_async, (), {
5  const result = await Promise.resolve(21);
6  return result * 2;
7});
8
9int main() {
10  int value = fetch_number_async();
11  std::printf("value=%d\n", value);
12  return 0;
13}

Compile with Asyncify enabled:

bash
emcc main.cpp -O2 -sASYNCIFY -o index.html

Without -sASYNCIFY, native stack suspension and resumption around Promise resolution does not work correctly.

Handle Promise Rejections Explicitly

Do not assume the JavaScript side always succeeds. Convert rejections into deterministic native return values or structured error payloads.

cpp
1EM_ASYNC_JS(int, load_count, (), {
2  try {
3    const r = await fetch('/data.json');
4    if (!r.ok) return -2;
5    const payload = await r.json();
6    return payload.count ?? -3;
7  } catch (e) {
8    console.error('load_count failed', e);
9    return -1;
10  }
11});

Native caller:

cpp
1int code = load_count();
2if (code < 0) {
3  std::printf("error=%d\n", code);
4} else {
5  std::printf("count=%d\n", code);
6}

Stable error mapping simplifies retries and telemetry.

Exchange Strings and Memory Safely

When JavaScript returns text to C or C++, allocate memory on the wasm heap and document ownership.

cpp
1EM_ASYNC_JS(char*, get_user_name, (), {
2  const name = await Promise.resolve('alice');
3  const len = lengthBytesUTF8(name) + 1;
4  const ptr = _malloc(len);
5  stringToUTF8(name, ptr, len);
6  return ptr;
7});
8
9int main() {
10  char* name = get_user_name();
11  std::printf("name=%s\n", name);
12  free(name);
13  return 0;
14}

If JS allocates, native side should free after use. Missing ownership rules is a common source of wasm memory leaks.

Alternative Pattern with ccall and Async JS Exports

In some architectures, JavaScript drives control and invokes exported wasm functions when Promise resolves. This avoids suspension on native side but changes program structure.

javascript
1async function start() {
2  const mod = await createModule();
3  const token = await getTokenFromApi();
4  mod.ccall('onTokenReady', null, ['string'], [token]);
5}
cpp
1extern "C" {
2  EMSCRIPTEN_KEEPALIVE
3  void onTokenReady(const char* token) {
4    std::printf("token=%s\n", token);
5  }
6}

Choose this pattern if your application is already event-driven from JavaScript entrypoints.

Build and Runtime Notes

Useful flags for async interop projects:

  • -sASYNCIFY for stack unwind and rewind
  • -sASSERTIONS=1 in debug builds for clearer runtime diagnostics
  • -gsource-map for debugging bridge failures in browser dev tools

Test both success and rejection paths in browser integration tests. Tiny demo success is not enough for production reliability.

Debug Async Boundary Failures

When native calls appear stuck, inspect browser console first for rejected Promises and Asyncify warnings. Add small trace logs on both sides of the bridge so you can verify call start, Promise resolution, and native resume order without guessing.

Common Pitfalls

  • Compiling Promise-based bridge code without Asyncify enabled.
  • Ignoring rejection handling and returning undefined native values.
  • Returning heap-allocated strings without clear ownership and free rules.
  • Mixing callback and async wrapper styles inconsistently across modules.
  • Verifying only happy-path behavior and skipping failure-path tests.

Summary

  • Use EM_ASYNC_JS plus Asyncify to await Promises from native code safely.
  • Map JS failures into explicit native error codes or structures.
  • Define memory ownership clearly when returning strings or buffers.
  • Choose one interop style per module for maintainability.
  • Validate both success and error paths in browser-level integration tests.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions