Skip to content

Commit

Permalink
More use of async/await keywords in JS library code. NFC
Browse files Browse the repository at this point in the history
  • Loading branch information
sbc100 committed Dec 15, 2024
1 parent dfe3356 commit 29e9866
Show file tree
Hide file tree
Showing 13 changed files with 72 additions and 66 deletions.
13 changes: 6 additions & 7 deletions src/embind/emval.js
Original file line number Diff line number Diff line change
Expand Up @@ -447,9 +447,9 @@ var LibraryEmVal = {
_emval_await__deps: ['$Emval', '$Asyncify'],
_emval_await__async: true,
_emval_await: (promise) => {
return Asyncify.handleAsync(() => {
promise = Emval.toValue(promise);
return promise.then(Emval.toHandle);
return Asyncify.handleAsync(async () => {
var value = await Emval.toValue(promise);
return Emval.toHandle(value);
});
},
#endif
Expand All @@ -468,10 +468,9 @@ var LibraryEmVal = {
},

_emval_coro_suspend__deps: ['$Emval', '_emval_coro_resume'],
_emval_coro_suspend: (promiseHandle, awaiterPtr) => {
Emval.toValue(promiseHandle).then(result => {
__emval_coro_resume(awaiterPtr, Emval.toHandle(result));
});
_emval_coro_suspend: async (promiseHandle, awaiterPtr) => {
var result = await Emval.toValue(promiseHandle);
__emval_coro_resume(awaiterPtr, Emval.toHandle(result));
},

_emval_coro_make_promise__deps: ['$Emval', '__cxa_rethrow'],
Expand Down
2 changes: 1 addition & 1 deletion src/jsifier.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,7 @@ function(${args}) {
MEMORY64 && rtnType == 'p' ? 'proxyToMainThreadPtr' : 'proxyToMainThread';
deps.push('$' + proxyFunc);
return `
function(${args}) {
${async_}function(${args}) {
if (ENVIRONMENT_IS_PTHREAD)
return ${proxyFunc}(${proxiedFunctionTable.length}, 0, ${+sync}${args ? ', ' : ''}${args});
${body}
Expand Down
9 changes: 6 additions & 3 deletions src/library_browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ var LibraryBrowser = {

// TODO: currently not callable from a pthread, but immediately calls onerror() if not on main thread.
emscripten_async_load_script__deps: ['$UTF8ToString'],
emscripten_async_load_script: (url, onload, onerror) => {
emscripten_async_load_script: async (url, onload, onerror) => {
url = UTF8ToString(url);
#if PTHREADS
if (ENVIRONMENT_IS_PTHREAD) {
Expand Down Expand Up @@ -687,10 +687,13 @@ var LibraryBrowser = {

#if ENVIRONMENT_MAY_BE_NODE && DYNAMIC_EXECUTION
if (ENVIRONMENT_IS_NODE) {
readAsync(url, false).then((data) => {
try {
var data = await readAsync(url, false);
eval(data);
loadDone();
}, loadError);
} catch {
loadError();
}
return;
}
#endif
Expand Down
34 changes: 17 additions & 17 deletions src/library_trace.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,29 +58,29 @@ var LibraryTracing = {
},

// Work around CORS issues ...
fetchBlob: (url) => {
return fetch(url).then((rsp) => rsp.blob());
fetchBlob: async (url) => {
var rsp = await fetch(url);
return rsp.blob();
},

configure: (collector_url, application) => {
configure: async (collector_url, application) => {
EmscriptenTrace.now = _emscripten_get_now;
var now = new Date();
var session_id = now.getTime().toString() + '_' +
Math.floor((Math.random() * 100) + 1).toString();
EmscriptenTrace.fetchBlob(collector_url + 'worker.js').then((blob) => {
EmscriptenTrace.worker = new Worker(window.URL.createObjectURL(blob));
EmscriptenTrace.worker.addEventListener('error', (e) => {
out('TRACE WORKER ERROR:');
out(e);
}, false);
EmscriptenTrace.worker.postMessage({ 'cmd': 'configure',
'data_version': EmscriptenTrace.DATA_VERSION,
'session_id': session_id,
'url': collector_url });
EmscriptenTrace.configured = true;
EmscriptenTrace.collectorEnabled = true;
EmscriptenTrace.postEnabled = true;
});
var blob = await EmscriptenTrace.fetchBlob(collector_url + 'worker.js');
EmscriptenTrace.worker = new Worker(window.URL.createObjectURL(blob));
EmscriptenTrace.worker.addEventListener('error', (e) => {
out('TRACE WORKER ERROR:');
out(e);
}, false);
EmscriptenTrace.worker.postMessage({ 'cmd': 'configure',
'data_version': EmscriptenTrace.DATA_VERSION,
'session_id': session_id,
'url': collector_url });
EmscriptenTrace.configured = true;
EmscriptenTrace.collectorEnabled = true;
EmscriptenTrace.postEnabled = true;
EmscriptenTrace.post([EmscriptenTrace.EVENT_APPLICATION_NAME, application]);
EmscriptenTrace.post([EmscriptenTrace.EVENT_SESSION_NAME, now.toISOString()]);
},
Expand Down
21 changes: 14 additions & 7 deletions src/library_webaudio.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ let LibraryWebAudio = {
return ctx && emscriptenRegisterAudioObject(new ctx(opts));
},

emscripten_resume_audio_context_async: (contextHandle, callback, userData) => {
emscripten_resume_audio_context_async: async (contextHandle, callback, userData) => {
function cb(state) {
#if WEBAUDIO_DEBUG
console.log(`emscripten_resume_audio_context_async() callback: New audio state="${EmAudio[contextHandle].state}", ID=${state}`);
Expand All @@ -83,7 +83,12 @@ let LibraryWebAudio = {
#if WEBAUDIO_DEBUG
console.log(`emscripten_resume_audio_context_async() resuming...`);
#endif
EmAudio[contextHandle].resume().then(() => { cb(1/*running*/) }).catch(() => { cb(0/*suspended*/) });
try {
await EmAudio[contextHandle].resume();
cb(1/*running*/);
} catch {
cb(0/*suspended*/);
}
},

emscripten_resume_audio_context_sync: (contextHandle) => {
Expand Down Expand Up @@ -138,7 +143,7 @@ let LibraryWebAudio = {
'$_wasmWorkersID',
'$_EmAudioDispatchProcessorCallback',
'$stackAlloc', '$stackRestore', '$stackSave'],
emscripten_start_wasm_audio_worklet_thread_async: (contextHandle, stackLowestAddress, stackSize, callback, userData) => {
emscripten_start_wasm_audio_worklet_thread_async: async (contextHandle, stackLowestAddress, stackSize, callback, userData) => {

#if ASSERTIONS
assert(contextHandle, `Called emscripten_start_wasm_audio_worklet_thread_async() with a null Web Audio Context handle!`);
Expand Down Expand Up @@ -183,7 +188,8 @@ let LibraryWebAudio = {

// TODO: In MINIMAL_RUNTIME builds, read this file off of a preloaded Blob,
// and/or embed from a string like with WASM_WORKERS==2 mode.
audioWorklet.addModule('{{{ TARGET_BASENAME }}}.aw.js').then(() => {
try {
await audioWorklet.addModule('{{{ TARGET_BASENAME }}}.aw.js');
#if WEBAUDIO_DEBUG
console.log(`emscripten_start_wasm_audio_worklet_thread_async() addModule('audioworklet.js') completed`);
#endif
Expand Down Expand Up @@ -211,19 +217,20 @@ let LibraryWebAudio = {
// either), but instead, the main thread must load all JS code into the
// worklet scope. Send the application main JS script to the audio
// worklet.
return audioWorklet.addModule(
await audioWorklet.addModule(
#if MINIMAL_RUNTIME
Module['js']
#else
Module['mainScriptUrlOrBlob'] || _scriptName
#endif
);
}).then(() => {
#if WEBAUDIO_DEBUG
console.log(`emscripten_start_wasm_audio_worklet_thread_async() addModule() of main application JS completed`);
#endif
{{{ makeDynCall('viii', 'callback') }}}(contextHandle, 1/*EM_TRUE*/, userData);
}).catch(audioWorkletCreationFailed);
} catch {
audioWorkletCreationFailed();
}
},

$_EmAudioDispatchProcessorCallback: (e) => {
Expand Down
9 changes: 5 additions & 4 deletions src/library_wget.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,25 +62,26 @@ var LibraryWget = {

emscripten_async_wget_data__deps: ['$asyncLoad', 'malloc', 'free', '$callUserCallback'],
emscripten_async_wget_data__proxy: 'sync',
emscripten_async_wget_data: (url, userdata, onload, onerror) => {
emscripten_async_wget_data: async (url, userdata, onload, onerror) => {
{{{ runtimeKeepalivePush() }}}
/* no need for run dependency, this is async but will not do any prepare etc. step */
asyncLoad(UTF8ToString(url)).then((byteArray) => {
try {
var byteArray = await asyncLoad(UTF8ToString(url));
{{{ runtimeKeepalivePop() }}}
callUserCallback(() => {
var buffer = _malloc(byteArray.length);
HEAPU8.set(byteArray, buffer);
{{{ makeDynCall('vppi', 'onload') }}}(userdata, buffer, byteArray.length);
_free(buffer);
});
}, () => {
} catch (e) {
if (onerror) {
{{{ runtimeKeepalivePop() }}}
callUserCallback(() => {
{{{ makeDynCall('vp', 'onerror') }}}(userdata);
});
}
});
}
},

emscripten_async_wget2__deps: ['$PATH_FS', '$wget', '$stackRestore', '$stringToUTF8OnStack'],
Expand Down
16 changes: 5 additions & 11 deletions src/postamble.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ dependenciesFulfilled = function runCaller() {

#if HAS_MAIN
#if MAIN_READS_PARAMS
function callMain(args = []) {
{{{ asyncIf(ASYNCIFY == 2) }}} function callMain(args = []) {
#else
function callMain() {
{{{ asyncIf(ASYNCIFY == 2) }}} function callMain() {
#endif
#if ASSERTIONS
assert(runDependencies == 0, 'cannot call main when async dependencies remain! (listen on Module["onRuntimeInitialized"])');
Expand Down Expand Up @@ -100,18 +100,12 @@ function callMain() {
// The current spec of JSPI returns a promise only if the function suspends
// and a plain value otherwise. This will likely change:
// https://github.com/WebAssembly/js-promise-integration/issues/11
Promise.resolve(ret).then((result) => {
exitJS(result, /* implicit = */ true);
}).catch((e) => {
handleException(e);
});
#else
ret = await ret;
#endif // ASYNCIFY == 2
// if we're not running an evented main loop, it's time to exit
exitJS(ret, /* implicit = */ true);
#endif // ASYNCIFY == 2
return ret;
}
catch (e) {
} catch (e) {
return handleException(e);
}
#if ABORT_ON_WASM_EXCEPTIONS
Expand Down
2 changes: 1 addition & 1 deletion src/preamble.js
Original file line number Diff line number Diff line change
Expand Up @@ -1087,7 +1087,7 @@ function getWasmImports() {
var result = await instantiateAsync(wasmBinary, wasmBinaryFile, info);
receiveInstantiationResult(result);
#if LOAD_SOURCE_MAP
receiveSourceMapJSON(await getSourceMapPromise());
receiveSourceMapJSON(await getSourceMapAsync());
#endif
return result;
#if MODULARIZE
Expand Down
13 changes: 8 additions & 5 deletions src/source_map_support.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,14 @@ function getSourceMap() {
return JSON.parse(UTF8ArrayToString(buf));
}

function getSourceMapPromise() {
async function getSourceMapAsync() {
if ((ENVIRONMENT_IS_WEB || ENVIRONMENT_IS_WORKER) && typeof fetch == 'function') {
return fetch(wasmSourceMapFile, {{{ makeModuleReceiveExpr('fetchSettings', "{ credentials: 'same-origin' }") }}})
.then((response) => response.json())
.catch(getSourceMap);
try {
var response = await fetch(wasmSourceMapFile, {{{ makeModuleReceiveExpr('fetchSettings', "{ credentials: 'same-origin' }") }}})
return response.json();
} catch {
// Fall back to getSourceMap below
}
}
return Promise.resolve(getSourceMap());
return getSourceMap();
}
13 changes: 6 additions & 7 deletions test/browser_reporting.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ var hasModule = typeof Module === 'object' && Module;

var reportingURL = 'http://localhost:8888/';

function reportResultToServer(result) {
async function reportResultToServer(result) {
if (reportResultToServer.reported) {
// Only report one result per test, even if the test misbehaves and tries to report more.
reportErrorToServer(`excessive reported results, sending ${result}, test will fail`);
Expand All @@ -11,12 +11,11 @@ function reportResultToServer(result) {
if ((typeof ENVIRONMENT_IS_NODE !== 'undefined' && ENVIRONMENT_IS_NODE) || (typeof ENVIRONMENT_IS_AUDIO_WORKLET !== 'undefined' && ENVIRONMENT_IS_AUDIO_WORKLET)) {
out(`RESULT: ${result}`);
} else {
fetch(`${reportingURL}/report_result?${encodeURIComponent(result)}`).then(() => {
if (typeof window === 'object' && window && hasModule && !Module['pageThrewException']) {
/* for easy debugging, don't close window on failure */
window.close();
}
});
await fetch(`${reportingURL}/report_result?${encodeURIComponent(result)}`);
if (typeof window === 'object' && window && hasModule && !Module['pageThrewException']) {
/* for easy debugging, don't close window on failure */
window.close();
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion test/other/test_unoptimized_code_size.js.size
Original file line number Diff line number Diff line change
@@ -1 +1 @@
54298
54297
2 changes: 1 addition & 1 deletion test/other/test_unoptimized_code_size_no_asserts.js.size
Original file line number Diff line number Diff line change
@@ -1 +1 @@
29718
29717
2 changes: 1 addition & 1 deletion test/other/test_unoptimized_code_size_strict.js.size
Original file line number Diff line number Diff line change
@@ -1 +1 @@
53094
53093

0 comments on commit 29e9866

Please sign in to comment.