emscripten-core / emscripten

Emscripten: An LLVM-to-WebAssembly Compiler
Other
25.91k stars 3.32k forks source link

WIP: await promise code from sync c #23043

Open hedwigz opened 2 days ago

hedwigz commented 2 days ago

Introduced a new macro MAIN_THREAD_EM_ASM_PROMISE_AWAIT which is used to write javascript code that returns a promise and block the C code from progressing until the promise is resolved (or errors).

int main()
{
  printf("1st print\n");
  // This call will block until the internal promise resolves (at least 1 second in this case) 
  MAIN_THREAD_EM_ASM_PROMISE_AWAIT({
    out('2nd print');
    // do some async operation that involves the main thread
    return new Promise((resolve,reject) => {
      setTimeout(() => {
        out('3rd print');
        resolve();
      }, 1000);
    });
  });
  printf("4th print\n");
  return 0;
}

The motivation for this was discussed before
We have multiple web workers, each of them calls javascript code which is async and has to be ran on the main thread and need to wait for the promise to be resolved.
I am open for suggestions on how to add this more elegantly