skip to Main Content

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

2

Answers


  1. an async function always returns a Promise, so you’re returning a Promise that returns an object with a .then method – but a proper .then method takes two arguments, both functions. onFulfilled and onRejected – your then function is not a valid Promise then

    To make it work, you’d write it something like this instead

    async function f() {
        return {
            then(onFulfilled, onRejected) {
                onFulfilled(42);
            }
        };
    }
    async function main() {
        let result=await f();
        console.log(result);
        f().then(result => console.log(result));
    }
    main();
    Login or Signup to reply.
  2. 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.

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