Skip to content
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

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

Open
absop opened this issue May 27, 2024 · 0 comments

Comments

@absop
Copy link

absop commented May 27, 2024

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}`);
    });

})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant