I am trying to create some sort of a benchmark app that would concurrently run WASM module and its’ equivalent JS function and then compare execution time of those two. I have tried using promises, callbacks, and the example from MDN with using await Promise.all(arrayOfPromises)
, but in each case JS function starts running after the WASM module is done.
Code is down below, ignore the DOM boilerplate:
import { default as wasm } from "./pkg/hello_world.js"
import { sortRandomArray } from "./src/sorting.js"
window.onload = () => {
const btn = document.getElementById("inputConfirmation");
addListeners(Array(btn), runTestAndPrintResult);
}
async function runWasmModule(sortRandomArray, arraySize) {
return new Promise(() => {
const time = parseFloat(sortRandomArray(arraySize));
console.log('wasm done ' + time);
});
}
async function runJSAlgo(sortRandomArray, arraySize) {
return new Promise(() => {
const time = sortRandomArray(arraySize) / 1000;
console.log('js done ' + time);
});
}
function addListeners(elements, fun) {
for (const element of elements) {
element.addEventListener("click", fun);
}
document.addEventListener("keypress", event => {
if (event.key === "Enter") {
fun();
}
})
}
const runTestAndPrintResult = async () => {
let arraySize = document.getElementById("arraySizeInput").value;
if (arraySize === "") {
return;
}
arraySize = parseInt(arraySize);
const n = document.createElement("h1");
if (arraySize <= 1) {
n.textContent = "Nice try :)";
document.body.appendChild(n);
return;
}
const wasmInstance = wasm();
wasmInstance.then(async (module) => {
await Promise.all([
runWasmModule(module.sort_random_array, arraySize),
runJSAlgo(sortRandomArray, arraySize),
]);
}).catch(err => {
console.error(err);
})
}
I do understand that JS is a single-threaded language but I got confused with all of the terms online about asynchronous nature. If there is no way to do this in JS, is there anything else I could try in order to realize this?