Wilco
Wilco

Reputation: 978

What are the return semantics of an async function?

I'm trying to wrap my head around the no-return-await rule.

Consider this snippet:

const a = async () => {
    return 5;
};

const b1 = async () => {
    return a();
};

const b2 = async () => {
    return await a();
};

const wut = async () => {
    console.log(await b1());
    console.log(await b2());
};

wut();

Every async function returns a promise, so a() returns a promise. In this case I expect that b1() also wraps a promise, so the result would be a nested promise. Retrieving the value would require a double await, like in b2, but this does not seem required as both console.log's return the value properly. What's going on? Are nested promises resolved recursively? I'm lost. Thanks for any pointers and explanation!

Upvotes: 0

Views: 54

Answers (1)

Quentin
Quentin

Reputation: 943591

This is how promises behave in general and is not specific to the async/await syntax.

If a promise is resolved with another promise, then it effectively turns itself into that promise instead of resolving immediately.

Upvotes: 1

Related Questions