Search code examples
javascriptasynchronouspromise

Is it possible that async function returns object having "then" function


The JavaScript async function(or regular function that returns Promise) regards any object that has function with "then" field as a Promise. So is it impossible to let such object as a resolved value of Promise?

Example: The function call await f() does not return result. If the field name of then is different name, it returns result.

async function f() {
    return {
        then() {
            //This function is just a function that somehow the name "then" is appropriate for.
            return 42;
        }
    };
}
async function main() {
    let result=await f();// it stops here.
    console.log(result);
    console.log(result.then());
}
main();

Solution

  • If you read the documentation about await you will notice

    await expression

    expression

    A Promise, a thenable object, or any value to wait for.

    And then you follow to the thenable docs, you will find that

    A thenable implements the .then() method

    and

    To interoperate with the existing Promise implementations, the language allows using thenables in place of promises.

    So, the combination of await and returning an object with a then method suggests to the js engine that this is a thenable object. So it expects it to have correctly implemented the thenable interface.