I’ll begin by showing what should be the expected output, both from a sensible view point and because it’s what happens if the functions weren’t async
.
about to resolve
about to return from foo
code right after awaited return from foo
about to return from bar
code right after awaited return from bar
But between returning from a function and executing the next line of code in the caller, Javascript is interleaving other code, resulting in the following:
about to resolve
about to return from foo
about to return from bar
code right after awaited return from foo
code right after awaited return from bar
I wonder if there’s a way to prevent it. I need the next line of code in the caller to be executed right after the async function returns.
That’s the output of the following code:
async function caller(cb) {
await cb();
console.log(`code right after awaited return from ${ cb.name }`);
}
const { promise, resolve } = Promise.withResolvers();
async function foo() {
await promise;
console.log('about to return from foo');
}
async function bar() {
await promise;
console.log('about to return from bar');
}
caller(foo);
caller(bar);
console.log('about to resolve');
resolve();
4
Answers
No, not in portable JavaScript. Using
await
is explicitly opting into yielding control and being resumed whenever the promise decides, necessarily involving a microtask in a microtask queue that you don’t locally control.Even in the cases when you can rely on a particular ordering of microtasks, doing so is a code smell. You should wait for any operations you depend on explicitly.
you could do
ofcourse the two caller calls will not be ran concurrently but sequentially (meaning caller(bar) will wait for caller(foo) to finish), but it sounds to me like that’s what you want.
EDIT: also the next line of code is in fact being called immediately after the async function returns, however the other async caller function is running concurrently in your code, so they’re not waiting for each other, which they are in the code i posted here, as "then" waits for the promise of the async function to resolve.
this would practically be pretty much the same as this:
Since caller() is an async function and await has not been called on it – it will execute in an async manner. This means it may move on to the next line of code, before execution has been completed,
If the order of execution matters ( you want to execute in an a sync manner ) you need to use await OR use .then()
You would need to fundamentally change the behavior of Promises. If you were to change your code to use
then
instead ofasync/await
this could work:However,
async/await
are tightly coupled to thePromise
type, so this won’t work usingasync/await
. I think creating a Promise-like object like this would only lead to confusion and future bugs. You’re probably better off thinking about why you need yourcaller
function to behave the way you’re describing, and make that an explicit part of your code’s APIs and patterns.