Javascript does not execute code right after an awaited call immediately (it does other stuff in between) after the async function returned

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.

Edit: It is also what would happen if foo and bar received “done” callbacks instead of Promise.then callbacks.

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

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.

6

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.

5

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()

1

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)
})()

EDIT: is this what you want, based on discussion below? (removed the code that was not what you wanted)

async function caller(cb) {
    await cb();
    console.log(`code right after awaited return from ${ cb.name }`);
    (async ()=>{
        //rest of caller code, there is no awaiting this, it will run however long it takes.
    })();
}

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');
}
(async ()=>{
    await caller(foo); // will wait until the point cb()/foo() has finished, it will not wait for the rest of the caller code.
    await caller(bar); // same as above
    //...etc.
})();
console.log('about to resolve');
resolve();

22

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật