Async/await function optimization issue
I'm using the Uglify version 3.17.4 package to minify code on the backend side to execute it later on frontend side like this:
const sourceCode = `async function myFetch() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/2");
const result = await response.text();
console.log('myFetch - after fetch', result);
} catch (error) {
console.log('myFetch - error', error);
}
}
async function main() {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const result = await response.text();
console.log('main - after fetch', result);
await myFetch();
// console.log('main - end'); // <-- THIS MAKES OR BREAKS IT
} catch (error) {
console.log('error', error);
}
}
await main();
console.log('FINISHED')`;
const minifiedRes = minify(sourceCode, {
module: true,
toplevel: true,
mangle: {
toplevel: true,
},
});
The minified code execution in browser is not correct without console.log('main-end') according to console.logs in browser and it seems like it doesn't await for myFetch function is done.
The minified code WITHOUT console.log looks like this:
try { var o = await(await fetch(\"https://jsonplaceholder.typicode.com/todos/1\")).text();console.log(\"main - after fetch\",o),async function(){try{var o=await(await fetch(\"https://jsonplaceholder.typicode.com/todos/2\")).text();console.log(\"myFetch - after fetch\",o)}catch(o){console.log(\"myFetch - error\",o)}}()}catch(o){console.log(\"error\",o)}await 0,console.log(\"finished\");
RESULT:

The code WITH console.log looks like this:
try{var o=await(await fetch(\"https://jsonplaceholder.typicode.com/todos/1\")).text();console.log(\"main - after fetch\",o);try{var t=await(await fetch(\"https://jsonplaceholder.typicode.com/todos/2\")).text();console.log(\"myFetch - after fetch\",t)}catch(o){console.log(\"myFetch - error\",o)}await 0,console.log(\"main - end\")}catch(o){console.log(\"error\",o)}await 0,console.log(\"finished\");
RESULT:

me too,but no problem before version 3.17.0 problem version version 3.17.1-3.17.4, feeling is caused by compress.awaits
source code
async function a() { return new Promise(r=>setTimeout(r, 1000)); } async function c(url, dstDir) { console.log('c') await b(); } async function b(files, dstDir) { console.log('b') try { const ret = await a('nodebuffer'); console.log('ok') } catch (err) { console.error('saveFiles catch error:', err); } } c().then(()=>{ console.log(1111); });
output
!(async function () { console.log("c"), (async function () { console.log("b"); try { await new Promise((o) => setTimeout(o, 1e3)); console.log("ok"); } catch (o) { console.error("saveFiles catch error:", o); } })(); })().then(() => { console.log(1111); });
await b() await is lost
Thanks for the detailed reports − investigating.
Patch released in [email protected]