Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run WebAssembly code async?

I have written a C function that I am able to execute from Angular/TypeScript/JavaScript using WebAssembly:

testWebAssembly() {
    Module.ccall("aCFunction", null, [], []); // takes a few seconds to finish
}

This function does some heavy mathematical calculations and needs a few seconds to finish. It is fired when a user clicks a button:

<button (click)="testWebAssembly()">Launch C function</button>

Is it possible to execute the function so that it does not block the UI of the web application?

I tried setTimeOut/async/Promise, but I don't seem to be able to make it work.

Thank you!

like image 373
andreas Avatar asked Jun 07 '18 01:06

andreas


People also ask

Is WebAssembly asynchronous?

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.

Does WebAssembly run natively?

WebAssembly is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages with low-level memory models such as C++ and Rust with a compilation target so that they can run on the web.

Is WebAssembly faster than JavaScript?

Unlike Javascript, WASM is statically typed, which means code optimization occurs far earlier in the compilation process before the code reaches the browser. Its binary files are considerably smaller than JavaScript's, resulting in significantly faster loading times.

How do I run a WebAssembly code?

To use WebAssembly in JavaScript, you first need to pull your module into memory before compilation/instantiation. This article provides a reference for the different mechanisms that can be used to fetch WebAssembly bytecode, as well as how to compile/instantiate then run it.


1 Answers

Asynchronous execution alone won't take it off the main thread. What you actually mean is executing it concurrently. The only way to achieve that on the Web is by using worker threads.

like image 91
Andreas Rossberg Avatar answered Oct 04 '22 12:10

Andreas Rossberg