Promise not working

Dear All,

Apologies, as I’m still working through async/await/Promises etc… I was wondering why a promise ‘Module’ in my code (which should wait for the download) seems to resolve too soon, hence breaking the notebook?

https://beta.observablehq.com/@sdwfrost/emscripten-webassembly-module-example#Module

You’re discovering some very interesting module loading patterns :slight_smile:

I suspect this one would be pretty confusing even just in JavaScript-land without Observable as an intermediate - the wassa module asynchronously loads, within itself, without using anything like AMD or UMD that would handle the asyncness. Digging at the example HTML file in their repo, they notify when the module is loaded with a Module.addOnPostRun( callback, and that works: here’s a working loader cell.

Module = new Promise(resolve => {
  require(url).catch(() =>
    window.Module.addOnPostRun(() => resolve(window.Module))
  );
})

So, it loads the JavaScript, and then waits for the stuff that JavaScript loads (its WebAssembly component, I’d expect), and then returns the usable Module object.

Dear @tom

As you can see from here, the addlOnPostRun function is used for benchmarking, and isn’t a generic pattern at all:

Module.addOnPostRun(() => {  // Run this stuff after the wasm module loads
          var start = window.performance.now();  //start timing
          var result = Module.ssa(x.rate, x.max_time, x.seed); //run our function
          var time = window.performance.now() - start;  //stop timing
          el.innerHTML = '<strong>Output: ' + result +  '<br />' + //print results
                         'Time Elapsed: ' + Math.round(time) + ' milliseconds</strong>';
          el.setAttribute("style", "margin:5px; padding:5px; border: thin solid #0000FF;");
        });

While it doesn’t matter for compilation what this function is, Emscripten has to be told about it (via -s "EXTRA_EXPORTED_RUNTIME_METHODS=['addOnPostRun']"). If this wasn’t there, is there any trick I could use within Observable to capture the asyncness?