The I/O APIs on the web are asynchronous, but they’re synchronous in most system languages. When compiling code to WebAssembly, you need to bridge one kind of APIs to another—and this bridge is Asyncify. In this post, you’ll learn when and how to use Asyncify and how it works under the hood.

I/O in system languages [#]

I’ll start with a simple example in C. Say, you want to read the user’s name from a file, and greet them with a “Hello, (username)!” message:

#include <stdio.h>

int main() {
    FILE *stream = fopen("name.txt", "r");
    char name[20+1];
    size_t len = fread(&name, 1, 20, stream);
    name[len] = '\0';
    printf("Hello, %s!\n", name);
    return 0;

While the example doesn’t do much, it already demonstrates something you’ll find in an application of any size: it reads some inputs from the external world, processes them internally and writes outputs back to the external world. All such interaction with the outside world happens via a few functions commonly called input-output functions, also shortened to I/O.

To read the name from C, you need at least two crucial I/O calls: fopen, to open the file, and fread to read data from it. Once you retrieve the data, you can use another I/O function printf to print the result to the console.

Those functions look quite simple at first glance and you don’t have to think twice about the machinery involved to read or write data. However, depending on the environment, there can be quite a lot going on inside:

  • If the input file is located on a local drive, the application needs to perform a series of memory and disk accesses to locate the file, check permissions, open it for reading, and then read block by block until the requested number of bytes is retrieved. This can be pretty slow, depending on the speed of your disk and the requested size.
  • Or, the input file might be located on a mounted network location, in which case, the network stack will now be involved too, increasing the complexity, latency and number of potential retries for each operation.
  • Finally, even printf is not guaranteed to print things to the console and might be redirected to a file or a network location, in which case it would have to go via the same steps above.


Using asynchronous web APIs from WebAssembly
1.10 GEEK