skip to Main Content

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


  1. I wonder if there’s a way to prevent it.

    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.

    Login or Signup to reply.
  2. you could do

    caller(foo).then(()=>{caller(bar)});
    

    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:

    (async ()=>{ 
        await caller(foo);
        await caller(bar)
    })()
    
    Login or Signup to reply.
  3. 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()

    Login or Signup to reply.
  4. You would need to fundamentally change the behavior of Promises. If you were to change your code to use then instead of async/await this could work:

    class DepthFirstPromise {
        constructor(executor) {
            this.handlers = [];
            this.resolvedValue = null;
            this.isResolved = false;
    
            if (executor) {
                executor(this.resolve.bind(this));
            }
        }
    
        resolve(value) {
            if (this.isResolved) return;
            this.isResolved = true;
            this.resolvedValue = value;
    
            // Execute handlers in depth-first fashion
            while (this.handlers.length) {
                const handler = this.handlers.shift();
                handler(value);
            }
        }
    
        then(onFulfilled) {
            const nextPromise = new DepthFirstPromise();
    
            const wrapper = (value) => {
                try {
                    const result = onFulfilled(value);
                    if (result && typeof result.then === 'function') {
                        result.then(nextPromise.resolve.bind(nextPromise));
                    } else {
                        nextPromise.resolve(result);
                    }
                } catch (err) {
                    nextPromise.resolve(Promise.reject(err));
                }
            };
    
            if (this.isResolved) {
                wrapper(this.resolvedValue);
            } else {
                this.handlers.push(wrapper);
            }
    
            return nextPromise;
        }
    
        static withResolvers() {
            const dfPromise = new DepthFirstPromise();
            return {
                promise: dfPromise,
                resolve: dfPromise.resolve.bind(dfPromise),
            };
        }
    }
    
    // Use the DepthFirstPromise
    const { promise, resolve } = DepthFirstPromise.withResolvers();
    
    function foo() {
        return promise.then(() => console.log("about to return from foo"));
    }
    
    function bar() {
        return promise.then(() => console.log("about to return from bar"));
    }
    
    function caller(cb) {
        return cb().then(() =>
            console.log(`code right after awaited return from ${cb.name}`)
        );
    }
    
    caller(foo);
    caller(bar);
    
    console.log("about to resolve");
    resolve();

    However, async/await are tightly coupled to the Promise type, so this won’t work using async/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 your caller function to behave the way you’re describing, and make that an explicit part of your code’s APIs and patterns.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search