0Pricing
WebAssembly (WASM) for High Performance Apps · 课时

使用 WASM 执行异步操作

使用 promise 和 async/await 实现异步模式,在不阻塞主线程的情况下处理 WASM 中的长时间运行任务

使用 WASM 执行异步操作 是 CoddyKit 上的免费 WebAssembly (WASM) for High Performance Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebAssembly (WASM) for High Performance Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Asynchronous WASM?

When a WebAssembly module performs a complex calculation or a long task, it can freeze your web page. This is because JavaScript is single-threaded, and most direct WASM calls are synchronous.

Asynchronous WASM patterns allow these tasks to run without completely blocking the main browser thread, keeping your UI responsive.

WASM's Synchronous Nature

When JavaScript calls an exported WASM function, that function executes entirely before JavaScript regains control. If the WASM function takes a long time, the browser's main thread will be blocked.

This means no UI updates, no user input processing, making the page appear frozen. True parallel execution for WASM often involves Web Workers, which is covered in another lesson.

Strategy: Breaking into Chunks

To prevent blocking the main thread, we can break a long-running WASM task into smaller, manageable chunks. Instead of one huge, blocking WASM call, we make many small ones.

Between each small WASM call, JavaScript can yield control back to the browser's event loop. This allows the UI to update and remain responsive.

WASM Function for a Chunk

Here's a Rust function that represents one "chunk" of work. It takes a starting value and performs a small number of calculations. In a real application, this could process a part of an image or a segment of data.

pub extern "C" fn process_chunk(start_val: u32, iterations: u32) -> u32 {
    let mut sum = start_val;
    for i in 0..iterations {
        sum = sum.wrapping_add(i); // Simulate work, prevent overflow
    }
    sum
}

Promises in JavaScript

To handle asynchronous operations, JavaScript uses Promises. A Promise represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

  • Pending: Initial state, neither fulfilled nor rejected.
  • Fulfilled: Operation completed successfully.
  • Rejected: Operation failed.

We use .then() for success and .catch() for errors.

Simplifying with async/await

async/await is syntactic sugar built on Promises, making asynchronous code look and behave more like synchronous code, improving readability. It's built on Promises.

  • An async function always returns a Promise.
  • The await keyword can only be used inside an async function. It pauses the execution until the Promise settles, allowing other tasks to run.

This is crucial for orchestrating our WASM chunks.

Making WASM Calls Yield

We can create a JavaScript utility function that wraps a synchronous WASM call in a Promise. By using setTimeout(..., 0), we tell the browser to execute the WASM call after the current event loop cycle finishes.

This effectively "yields" control back to the browser, allowing it to update the UI before the next WASM chunk runs.

function callWasmAsync(wasmExports, funcName, ...args) {
  return new Promise(resolve => {
    setTimeout(() => {
      const result = wasmExports[funcName](...args);
      resolve(result);
    }, 0); // Yield control to the event loop
  });
}

Full Async WASM Example

Here's a complete, runnable example demonstrating how to manage a long-running WASM task asynchronously using chunking and JavaScript's async/await.

Notice how `setTimeout(0)` around the WASM call allows the browser to breathe between chunks.

// main.js
// Assume wasm_module.wasm (containing process_chunk) is loaded.
// For this runnable example, we'll simulate the WASM function.

// This simulates our WASM module's process_chunk function
function simulateWasmProcessChunk(start_val, iterations) {
    let sum = start_val;
    for (let i = 0; i < iterations; i++) {
        sum = (sum + i) % 10000; // Simplified calculation
    }
    return sum;
}

// Utility to call a synchronous task asynchronously
function callSyncTaskAsync(taskFunc, ...args) {
  return new Promise(resolve => {
    setTimeout(() => {
      const result = taskFunc(...args);
      resolve(result);
    }, 0); // Yield control to the event loop
  });
}

async function performLongTask() {
  console.log("Starting async task...");
  let currentSum = 0;
  const totalChunks = 5;
  const iterationsPerChunk = 10_000_000; // Simulate heavy work

  for (let i = 0; i < totalChunks; i++) {
    // Call the simulated WASM chunk asynchronously
    currentSum = await callSyncTaskAsync(
      simulateWasmProcessChunk,
      currentSum,
      iterationsPerChunk
    );
    console.log(`Chunk ${i + 1} done. Current sum: ${currentSum}`);
  }
  console.log("Async task finished. Final sum:", currentSum);
  return currentSum;
}

performLongTask();

Handling Errors Asynchronously

Just like any asynchronous operation, you should handle potential errors. If a WASM chunk call fails (e.g., due to invalid input or memory issues), the Promise will reject.

You can use try...catch with async/await or .catch() with Promises to gracefully handle these situations in your JavaScript code.

Async WASM Check

Consider a WebAssembly function heavy_calc() that takes 5 seconds to run. If you call it directly from JavaScript's main thread, what is the primary consequence?

Recap: Async WASM Patterns

We've learned how to handle long-running WASM tasks asynchronously on the main thread without using Web Workers. Key takeaways:

  • WASM functions are synchronous when called from JavaScript.
  • Break long tasks into smaller "chunks."
  • Use JavaScript Promises and async/await to orchestrate these chunks.
  • Yield control to the browser's event loop (e.g., with setTimeout(0)) between chunk calls to keep the UI responsive.

This pattern is crucial for maintaining a smooth user experience in complex web applications.

常见问题解答

「使用 WASM 执行异步操作」课时是免费的吗?

是的 — 「使用 WASM 执行异步操作」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebAssembly (WASM) for High Performance Apps 课程的其余内容,请升级到 CoddyKit PRO。 WebAssembly (WASM) for High Performance Apps 课程共包含 4 节课。

「使用 WASM 执行异步操作」这节课中我会学到什么?

使用 promise 和 async/await 实现异步模式,在不阻塞主线程的情况下处理 WASM 中的长时间运行任务 你通过在浏览器中直接运行的动手代码来练习 WebAssembly (WASM) for High Performance Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebAssembly (WASM) for High Performance Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebAssembly (WASM) for High Performance Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「使用 WASM 执行异步操作」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebAssembly (WASM) for High Performance Apps 课中编写并运行代码吗?

能。每节 WebAssembly (WASM) for High Performance Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 WASM 执行异步操作
  2. 自定义 JavaScript 回调
  3. 错误处理与异常
  4. 跨 JS/WASM 边界共享内存与类型化数组
← 返回 WebAssembly (WASM) for High Performance Apps