Trying to understand how control is yielded and resumed in async code

If a .then is chained to the promise, the code after the await does run. That is the difference, as using the then to register a callback is quit common in JavaScript.

Modifying your javascript version

async function main() {

    let res1 = async () => {
        await sleeep();
    };

    let res2 = async () => {
        await sleeep();
    };

    res1().then(() => console.log("Done res1"));
    console.log("This line runs")
    res2().then(() => console.log("Done res2"));

    console.log("hello world");
}

async function sleeep() {
    console.log("entered sleeping");
    await sleep(2000);
    console.log("done sleeping");
}

function sleep(durationMs) {
    return new Promise((resolve) => setTimeout(resolve, durationMs));
}

Output is

entered sleeping
This line runs
entered sleeping
hello world
done sleeping
Done res1
done sleeping
Done res2

But you are correct, if the promise itself is awaited, the behavior is same as in async Rust.

In Rust and JS, awaits always suspend the async function/block that directly encloses them, and no other. In your modified code,

    let res2 = async () => {
        await sleeep();
    };

the await that it contains is suspending the anonymous async function, not main(). That's the key difference. As long as there is no await directly within main(), main() will continue whether or not you also use a then().

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.