JavaScript Promise Integration (JSPI) 是一種 API,可讓編譯為 WebAssembly 的同步循序程式碼存取非同步 Web API。許多 Web API 都是以 JavaScript Promise 形式設計:這些 API 不會立即執行所要求的作業,而是傳回 Promise 來執行作業。當動作最終執行時,瀏覽器的工作執行器會使用 Promise 叫用任何回呼。JSPI 會連結至這個架構,以便在傳回 Promise 時暫停 WebAssembly 應用程式,並在 Promise 解決時繼續執行。
從 Chrome 123 版到 Chrome 128 版,JSPI 將以來源試用形式提供。如要進一步瞭解 JSPI,請參閱「Introducing the WebAssembly JavaScript Promise Integration API」網誌文章,或規格草案。
如要進一步瞭解如何使用這項功能,請參考下列 C 程式碼片段,該程式碼會將加法運算外包給 JavaScript 函式,藉此計算費波那契數列。
// This is C code.
long promiseFib(long x) {
if (x == 0)
return 0;
if (x == 1)
return 1;
// This is where the C code calls asynchronous JavaScript.
return promiseAdd(promiseFib(x - 1), promiseFib(x - 2));
}
// Addition artificially wrapped in a Promise.
EM_ASYNC_JS(long, promiseAdd, (long x, long y), {
// This is asynchronous JavaScript code.
return Promise.resolve(x+y);
});
如要將這個 C 程式編譯為 WebAssembly,請使用下列指令,這需要 Emscripten SDK。
emcc -O3 badfib.c -o index.html -s ASYNCIFY=2
您可以透過 JavaScript 偵測 JSPI 支援情形,如下所示:
if ('Suspender' in WebAssembly) {
// JSPI is supported.
}
如要與應用程式的實際使用者一起試用 JSPI,請註冊原始碼試用計畫。如需操作說明,請參閱「開始使用來源試用計畫」。JSPI 團隊很期待收到您的原始碼試用意見回饋 (請參閱操作說明中的步驟 5),確保這項功能在發布時符合您的需求!