JS WebAssembly.compileStreaming()
WebAssembly.compileStreaming()
方法用来从一个流式源中直接编译一个 WebAssembly.Module
。当模块需要在被实例化前被编译时,这个方法会很有用。如果要从流式源实例化一个模块应采用 WebAssembly.instantiateStreaming()
方法。
语法
Promise WebAssembly.compileStreaming(source);
参数
source
一个 Response
对象或一个会履行(fulfill)它的 promise,用来表示你想编译的 .wasm 模块的流式源。
返回值
一个会被解决(resolve)为编译后的 WebAssembly.Module
对象的 Promise
。
异常
- 如果
bufferSource
不是一个 typed array,将会抛出TypeError
异常。 - 如果编译失败,promise 会通过拒绝(reject)来返回一个
WebAssembly.CompileError
。
例子
下面的例子(在 GitHub 上查看我们的 compile-streaming.html 示例或者直接在线预览)直接从流式源传输一个 .wasm 模块然后将其编译为一个 WebAssembly.Module
对象。因为 compileStreaming()
方法可以接受一个结果为 Response
对象的 promise,因此你可以直接用 WindowOrWorkerGlobalScope.fetch()
的调用结果来调用该方法。
var importObject = { imports: { imported_func: arg => console.log(arg) } };
WebAssembly.compileStreaming(fetch('simple.wasm'))
.then(module => WebAssembly.instantiate(module, importObject))
.then(instance => instance.exports.exported_func());
得到的 module 实例接下来通过 WebAssembly.instantiate()
方法被实例化了,然后调用模块导出的函数。
Specifications
Specification | Status | Comment |
---|---|---|
[WebAssembly features for web embedding | ||
compileStreaming()](https://github.com/WebAssembly/design/blob/master/Web.md#webassemblycompilestreaming) | Draft | Initial draft definition. |