Async / await in a class method called "then"

I created a class that has a "then" method. This class is not associated with the Promise type; the "then" method has a different purpose and does not return a promise. I am trying to write an async / await function in Typescript 2.1.4 that expects and returns an instance of this class, but the Typescript server in VS Code gives me errors. If I rename the method to something other than "then", the errors disappear.

Example code with errors:

class MyClass {
    then(): number {
        // this method isn't related to Promise.then
        return 2 + 2;
    }
}

// three errors below go away when "then" is renamed

// [ts] An async function or method must have a valid awaitable return type.
async function my_async(): Promise<MyClass> {
    let a: Promise<MyClass> = Promise.resolve(new MyClass());

    // [ts] Operand for 'await' does not have a valid callable 'then' member.
    let b: MyClass = await a;

    // [ts] Return expression in async function does not have a valid callable 'then' member.
    return b;
}

Can someone explain why using promises with an object that has its own "then" method is not allowed or works?

+4
source share
2

then API Promise - ducktyping JavaScript, thenable . ,

...
Let then be Get(resolution, "then").
...

, then, - a thenable. , then Promise.

+3

Promises .then. , , ", require('bluebird/promise')".

, , , , , , .then, . :

function myFn() {
  // doPromise1 will eventually give us `1`.
  return doPromise1().then(x => {
    // doPromise2 will eventually give us `2`.
    return doPromise2();
  });
}

.then , doPromise2(). 2 - promises .

, 3 then. , , . , , . typechecking, if p instanceof Promise, , . - , : if (typeof p.then === 'function').

true , , - . , , .

+3

Source: https://habr.com/ru/post/1663663/


All Articles