bellard / quickjs

Public repository of the QuickJS Javascript Engine.
https://bellard.org/quickjs
Other
8.51k stars 892 forks source link

[async/module] Strange behavior when running async function with the `--module` option #310

Open absop opened 5 months ago

absop commented 5 months ago

Executing the following script with the --module option produces strange results.

Screenshot of running results: image

The script (test-async-sleep.js):


(async () => {
    if (globalThis.setTimeout === undefined) {
        console.log("Trying to import 'os' module");
        const os = await import('os');
        globalThis.setTimeout = os.setTimeout;
        console.log(`globalThis.setTimeout = ${globalThis.setTimeout}`);
    }

    const sleep = (ms) =>
      new Promise(resolve => setTimeout(resolve, ms));

    async function gen(ident, count, delay) {
        var curr, cost;
        var last = Date.now();
        var i, total = 0;
        for (i = 0; i < count; ++i) {
            await sleep(delay);
            curr = Date.now();
            cost = curr - last;
            last = curr;
            total += cost;
            console.log(`${ident}: ${i}, curr = ${curr}, cost = ${cost}`);
        }
        return total / count;
    }

    var g1 = gen(1, 1, 100);
    var g2 = gen(2, 2, 100);
    var g3 = gen(3, 2, 100);

    c1 = await g1;
    // c2 = await g2;
    // c3 = await g3;
    console.log(`averageCost = ${c1}`);
    // console.log(`averageCost = ${c2}`);

    g2.then((cost) => {
        console.log(`averageCost = ${cost}`);
    });

    g3.then((cost) => {
        console.log(`averageCost = ${cost}`);
    });

})();