Skip to content

Commit 6008fc8

Browse files
committed
Use async/await instead of promises for wasm loading. NFC
These get lowered away by babel when targetting older engines.
1 parent 78c968b commit 6008fc8

File tree

85 files changed

+205
-206
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

85 files changed

+205
-206
lines changed

src/library.js

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2182,19 +2182,15 @@ addToLibrary({
21822182
},
21832183

21842184
$asyncLoad__docs: '/** @param {boolean=} noRunDep */',
2185-
$asyncLoad: (url, noRunDep) => {
2186-
return new Promise((resolve, reject) => {
2187-
var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : '';
2188-
if (dep) addRunDependency(dep);
2189-
readAsync(url).then(
2190-
(arrayBuffer) => {
2185+
$asyncLoad: async (url, noRunDep) => {
2186+
var dep = !noRunDep ? getUniqueRunDependency(`al ${url}`) : '';
2187+
if (dep) addRunDependency(dep);
2188+
var arrayBuffer = await readAsync(url);
21912189
#if ASSERTIONS
2192-
assert(arrayBuffer, `Loading data file "${url}" failed (no arrayBuffer).`);
2190+
assert(arrayBuffer, `Loading data file "${url}" failed (no arrayBuffer).`);
21932191
#endif
2194-
resolve(new Uint8Array(arrayBuffer));
2195-
if (dep) removeRunDependency(dep);
2196-
}, reject);
2197-
});
2192+
if (dep) removeRunDependency(dep);
2193+
return new Uint8Array(arrayBuffer);
21982194
},
21992195

22002196
$alignMemory: (size, alignment) => {

src/preamble.js

Lines changed: 94 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -645,7 +645,7 @@ function getBinarySync(file) {
645645
#endif
646646
}
647647

648-
function getBinaryPromise(binaryFile) {
648+
async function getWasmBinary(binaryFile) {
649649
#if !SINGLE_FILE
650650
// If we don't have the binary yet, load it asynchronously using readAsync.
651651
if (!wasmBinary
@@ -654,16 +654,18 @@ function getBinaryPromise(binaryFile) {
654654
#endif
655655
) {
656656
// Fetch the binary using readAsync
657-
return readAsync(binaryFile).then(
658-
(response) => new Uint8Array(/** @type{!ArrayBuffer} */(response)),
659-
// Fall back to getBinarySync if readAsync fails
660-
() => getBinarySync(binaryFile)
661-
);
657+
try {
658+
/** @type{!ArrayBuffer} */
659+
var response = await readAsync(binaryFile);
660+
return new Uint8Array(response);
661+
} catch {
662+
// Fall back to getBinarySync below;
663+
}
662664
}
663665
#endif
664666

665667
// Otherwise, getBinarySync should be able to get it synchronously
666-
return Promise.resolve(getBinarySync(binaryFile));
668+
return getBinarySync(binaryFile);
667669
}
668670

669671
#if LOAD_SOURCE_MAP
@@ -771,56 +773,47 @@ function resetPrototype(constructor, attrs) {
771773
#endif
772774

773775
#if WASM_ASYNC_COMPILATION
774-
function instantiateArrayBuffer(binaryFile, imports) {
776+
async function instantiateArrayBuffer(binaryFile, imports) {
777+
try {
778+
var binary = await getWasmBinary(binaryFile);
779+
var instance = await WebAssembly.instantiate(binary, imports);
775780
#if USE_OFFSET_CONVERTER
776-
var savedBinary;
781+
// wasmOffsetConverter needs to be assigned before calling resolve.
782+
// See comments below in instantiateAsync.
783+
wasmOffsetConverter = new WasmOffsetConverter(binary, instance.module);
777784
#endif
778-
return new Promise((resolve, reject) => {
779-
getBinaryPromise(binaryFile).then((binary) => {
780-
#if USE_OFFSET_CONVERTER
781-
savedBinary = binary;
782-
#endif
783-
return WebAssembly.instantiate(binary, imports);
784-
#if USE_OFFSET_CONVERTER
785-
}).then((instance) => {
786-
// wasmOffsetConverter needs to be assigned before calling resolve.
787-
// See comments below in instantiateAsync.
788-
wasmOffsetConverter = new WasmOffsetConverter(savedBinary, instance.module);
789-
return instance;
790-
#endif
791-
}).then(resolve, (reason) => {
792-
err(`failed to asynchronously prepare wasm: ${reason}`);
793-
785+
return instance;
786+
} catch (reason) {
787+
err(`failed to asynchronously prepare wasm: ${reason}`);
794788
#if WASM == 2
795789
#if ENVIRONMENT_MAY_BE_NODE || ENVIRONMENT_MAY_BE_SHELL
796-
if (typeof location != 'undefined') {
797-
#endif
798-
// WebAssembly compilation failed, try running the JS fallback instead.
799-
var search = location.search;
800-
if (search.indexOf('_rwasm=0') < 0) {
801-
location.href += (search ? search + '&' : '?') + '_rwasm=0';
802-
// Return here to avoid calling abort() below. The application
803-
// still has a chance to start successfully do we don't want to
804-
// trigger onAbort or onExit handlers.
805-
return;
806-
}
807-
#if ENVIRONMENT_MAY_BE_NODE || ENVIRONMENT_MAY_BE_SHELL
790+
if (typeof location != 'undefined') {
791+
#endif
792+
// WebAssembly compilation failed, try running the JS fallback instead.
793+
var search = location.search;
794+
if (search.indexOf('_rwasm=0') < 0) {
795+
location.href += (search ? search + '&' : '?') + '_rwasm=0';
796+
// Return here to avoid calling abort() below. The application
797+
// still has a chance to start successfully do we don't want to
798+
// trigger onAbort or onExit handlers.
799+
return;
808800
}
801+
#if ENVIRONMENT_MAY_BE_NODE || ENVIRONMENT_MAY_BE_SHELL
802+
}
809803
#endif
810804
#endif // WASM == 2
811805

812806
#if ASSERTIONS
813-
// Warn on some common problems.
814-
if (isFileURI(wasmBinaryFile)) {
815-
err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`);
816-
}
807+
// Warn on some common problems.
808+
if (isFileURI(wasmBinaryFile)) {
809+
err(`warning: Loading from a file URI (${wasmBinaryFile}) is not supported in most browsers. See https://emscripten.org/docs/getting_started/FAQ.html#how-do-i-run-a-local-webserver-for-testing-why-does-my-program-stall-in-downloading-or-preparing`);
810+
}
817811
#endif
818-
abort(reason);
819-
});
820-
});
812+
abort(reason);
813+
}
821814
}
822815

823-
function instantiateAsync(binary, binaryFile, imports) {
816+
async function instantiateAsync(binary, binaryFile, imports) {
824817
#if !SINGLE_FILE
825818
if (!binary &&
826819
typeof WebAssembly.instantiateStreaming == 'function' &&
@@ -839,56 +832,46 @@ function instantiateAsync(binary, binaryFile, imports) {
839832
!ENVIRONMENT_IS_NODE &&
840833
#endif
841834
typeof fetch == 'function') {
842-
return new Promise((resolve) => {
843-
fetch(binaryFile, {{{ makeModuleReceiveExpr('fetchSettings', "{ credentials: 'same-origin' }") }}}).then((response) => {
844-
// Suppress closure warning here since the upstream definition for
845-
// instantiateStreaming only allows Promise<Repsponse> rather than
846-
// an actual Response.
847-
// TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.
848-
/** @suppress {checkTypes} */
849-
var result = WebAssembly.instantiateStreaming(response, imports);
835+
try {
836+
var response = await fetch(binaryFile, {{{ makeModuleReceiveExpr('fetchSettings', "{ credentials: 'same-origin' }") }}});
837+
// Suppress closure warning here since the upstream definition for
838+
// instantiateStreaming only allows Promise<Repsponse> rather than
839+
// an actual Response.
840+
// TODO(https://github.com/google/closure-compiler/pull/3913): Remove if/when upstream closure is fixed.
841+
/** @suppress {checkTypes} */
842+
var result = WebAssembly.instantiateStreaming(response, imports);
850843

851844
#if USE_OFFSET_CONVERTER
852-
// We need the wasm binary for the offset converter. Clone the response
853-
// in order to get its arrayBuffer (cloning should be more efficient
854-
// than doing another entire request).
855-
// (We must clone the response now in order to use it later, as if we
856-
// try to clone it asynchronously lower down then we will get a
857-
// "response was already consumed" error.)
858-
var clonedResponsePromise = response.clone().arrayBuffer();
845+
// We need the wasm binary for the offset converter. Clone the response
846+
// in order to get its arrayBuffer (cloning should be more efficient
847+
// than doing another entire request).
848+
// (We must clone the response now in order to use it later, as if we
849+
// try to clone it asynchronously lower down then we will get a
850+
// "response was already consumed" error.)
851+
var arrayBufferResult = await response.clone().arrayBuffer();
852+
// When using the offset converter, we must interpose here. First,
853+
// the instantiation result must arrive (if it fails, the error
854+
// handling later down will handle it). Once it arrives, we can
855+
// initialize the offset converter. And only then is it valid to
856+
// call receiveInstantiationResult, as that function will use the
857+
// offset converter (in the case of pthreads, it will create the
858+
// pthreads and send them the offsets along with the wasm instance).
859+
var instantiationResult = await result;
860+
try {
861+
wasmOffsetConverter = new WasmOffsetConverter(new Uint8Array(arrayBufferResult), instantiationResult.module);
862+
} catch (reason) {
863+
err(`failed to initialize offset-converter: ${reason}`);
864+
}
859865
#endif
860866

861-
result.then(
862-
#if USE_OFFSET_CONVERTER
863-
(instantiationResult) => {
864-
// When using the offset converter, we must interpose here. First,
865-
// the instantiation result must arrive (if it fails, the error
866-
// handling later down will handle it). Once it arrives, we can
867-
// initialize the offset converter. And only then is it valid to
868-
// call receiveInstantiationResult, as that function will use the
869-
// offset converter (in the case of pthreads, it will create the
870-
// pthreads and send them the offsets along with the wasm instance).
871-
872-
clonedResponsePromise.then((arrayBufferResult) => {
873-
wasmOffsetConverter = new WasmOffsetConverter(new Uint8Array(arrayBufferResult), instantiationResult.module);
874-
resolve(instantiationResult);
875-
},
876-
(reason) => err(`failed to initialize offset-converter: ${reason}`)
877-
);
878-
},
879-
#else
880-
resolve,
881-
#endif
882-
(reason) => {
883-
// We expect the most common failure cause to be a bad MIME type for the binary,
884-
// in which case falling back to ArrayBuffer instantiation should work.
885-
err(`wasm streaming compile failed: ${reason}`);
886-
err('falling back to ArrayBuffer instantiation');
887-
return resolve(instantiateArrayBuffer(binaryFile, imports));
888-
}
889-
);
890-
});
891-
});
867+
return result;
868+
} catch (reason) {
869+
// We expect the most common failure cause to be a bad MIME type for the binary,
870+
// in which case falling back to ArrayBuffer instantiation should work.
871+
err(`wasm streaming compile failed: ${reason}`);
872+
err('falling back to ArrayBuffer instantiation');
873+
return instantiateArrayBuffer(binaryFile, imports);
874+
};
892875
}
893876
#endif
894877
return instantiateArrayBuffer(binaryFile, imports);
@@ -934,7 +917,13 @@ function getWasmImports() {
934917

935918
// Create the wasm instance.
936919
// Receives the wasm imports, returns the exports.
920+
#if WASM_ASYNC_COMPILATION
921+
// Funnily enough in JS the `async` keyword has to be on the same line as the
922+
// function keyword.
923+
async function createWasm() {
924+
#else
937925
function createWasm() {
926+
#endif
938927
// Load the wasm module and create an instance of using native support in the JS engine.
939928
// handle a generated wasm instance, receiving its exports and
940929
// performing other necessary setup
@@ -1102,17 +1091,23 @@ function createWasm() {
11021091
#if RUNTIME_DEBUG
11031092
dbg('asynchronously preparing wasm');
11041093
#endif
1105-
instantiateAsync(wasmBinary, wasmBinaryFile, info).then(receiveInstantiationResult)
11061094
#if MODULARIZE
1107-
// If instantiation fails, reject the module ready promise.
1108-
.catch(readyPromiseReject)
1095+
try {
11091096
#endif
1110-
;
1097+
var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);
1098+
receiveInstantiationResult(result);
11111099
#if LOAD_SOURCE_MAP
1112-
getSourceMapPromise().then(receiveSourceMapJSON);
1100+
receiveSourceMapJSON(await getSourceMapPromise());
11131101
#endif
1114-
return {}; // no exports yet; we'll fill them in later
1115-
#else
1102+
return result;
1103+
#if MODULARIZE
1104+
} catch (e) {
1105+
// If instantiation fails, reject the module ready promise.
1106+
readyPromiseReject(e);
1107+
throw e;
1108+
}
1109+
#endif
1110+
#else // WASM_ASYNC_COMPILATION
11161111
var result = instantiateSync(wasmBinaryFile, info);
11171112
#if PTHREADS || MAIN_MODULE
11181113
return receiveInstance(result[0], result[1]);
@@ -1122,7 +1117,7 @@ function createWasm() {
11221117
// When the regression is fixed, we can remove this if/else.
11231118
return receiveInstance(result[0]);
11241119
#endif
1125-
#endif
1120+
#endif // WASM_ASYNC_COMPILATION
11261121
}
11271122

11281123
#if !WASM_BIGINT
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
8534
1+
8515
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
20856
1+
20823
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
8518
1+
8503
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
20824
1+
20791
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
9563
1+
9552
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
24699
1+
24668
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
8500
1+
8486
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
20750
1+
20718

0 commit comments

Comments
 (0)