Skip to content

Commit 46cbd19

Browse files
RReverseralexcrichton
authored andcommitted
Improve worker.js reliability (#1820)
While it doesn't happen right now in this particular example, `lastPtr` can be potentially overridden several times before the module is fully initialised. Rather than having a boolean and a storage for one last argument, `await` a promise returned from `wasm_bindgen` itself in the new `onmessage` handler before executing actual command. This way all the potential tasks will queue up naturally, wait for the initialisation, and then execute in a correct order.
1 parent a31b813 commit 46cbd19

File tree

1 file changed

+15
-26
lines changed

1 file changed

+15
-26
lines changed

examples/raytrace-parallel/worker.js

+15-26
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,25 @@
11
// synchronously, using the browser, import out shim JS scripts
22
importScripts('raytrace_parallel.js');
33

4-
let booted = false;
5-
let lastPtr = null;
6-
74
// Wait for the main thread to send us the shared module/memory. Once we've got
85
// it, initialize it all with the `wasm_bindgen` global we imported via
96
// `importScripts`.
107
//
118
// After our first message all subsequent messages are an entry point to run,
129
// so we just do that.
13-
self.onmessage = function(args) {
14-
self.onmessage = event => run(event.data);
15-
const [module, memory] = args.data;
16-
wasm_bindgen(module, memory)
17-
.then(() => {
18-
booted = true;
19-
if (lastPtr)
20-
run(lastPtr);
21-
})
22-
.catch(e => setTimeout(() => { throw e; })); // propagate to main `onerror`
23-
};
10+
self.onmessage = event => {
11+
let initialised = wasm_bindgen(...event.data).catch(err => {
12+
// Propagate to main `onerror`:
13+
setTimeout(() => {
14+
throw err;
15+
});
16+
// Rethrow to keep promise rejected and prevent execution of further commands:
17+
throw err;
18+
});
2419

25-
function run(ptr) {
26-
if (!booted) {
27-
lastPtr = ptr;
28-
return;
29-
}
30-
lastPtr = null;
31-
try {
32-
wasm_bindgen.child_entry_point(ptr);
33-
} catch (e) {
34-
throw new Error(e.message + "\n\n" + e.stack);
35-
}
36-
}
20+
self.onmessage = async event => {
21+
// This will queue further commands up until the module is fully initialised:
22+
await initialised;
23+
wasm_bindgen.child_entry_point(event.data);
24+
};
25+
};

0 commit comments

Comments
 (0)