Skip to content

More use of async/await keywords in JS library code. NFC #23150

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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 @@ -1091,7 +1091,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) {
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 @@
53981
53980
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 @@
29401
29400
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 @@
52777
52776
Loading