Asyncify and waiting for exported function to finish

32 views
Skip to first unread message

Soeren Balko

unread,
Oct 25, 2023, 12:39:33 AM10/25/23
to emscripten-discuss
First time looking into Asyncify again. Impressed with the improvements since I last looked into it!

One question: I am calling some exported top-level function that may or may not call some nested asynchronous function. If it does, then waiting on the promise returned by `Asyncify.whenDone()` gives me the function's result. If the top-level function does not call the nested asynchronous function, then its result is synchronously returned. 

The only way for me to know whether or not I need to wait on `Asyncify.whenDone()` is to check whether `Asyncify.currData === null`. 

Is this how it is supposed to be? So something like:

```
async function callExportedFunction() {
   const syncResult = Module.topLevelFunction();

    if (Asyncify.currData === null) return syncResult;

     return Asyncify.whenDone();
}
```

This works, but seems inconsistent and unnecessarily complex. Could the exported function always directly return a promise? Or at least, can `Asyncify.whenDone()` resolve immediately when the result is synchronously available?

Soeren

Brendan Dahl

unread,
Oct 26, 2023, 6:45:39 PM10/26/23
to emscripten-discuss
Yes, that's currently the best way to handle that situation and what embind currently does

As for it being complex, yes. This was an optimization so that functions that don't need to suspend don't have to return the micro task queue. It also made it so code that would only trigger the sync behaviour didn't need to be re-written to handle the async version.

FWIW, with JSPI (what will hopefully replace asyncify) async exports will always return a promise. We've been discussing changing asyncify to match this behavior, but there are downsides as mentioned above. 

Reply all
Reply to author
Forward
0 new messages