0

When i run this code:

    class Thenable {
  constructor(num) {
    this.num = num;
  }
  then(resolve, reject) {
    console.log(resolve);
    
    setTimeout(() => resolve(this.num * 4), 1000); 
  }
};

async function f() {

  let result = await new Thenable(1); //then() method is called automatically
  console.log(result); 
}

f();

I noticed that then() method is called without explicit call.

I was surprised, because i thought when javascript meets await then it just automatically returns resolved value inside executor function like in this code:

async function f() {

  let promise = new Promise((resolve, reject) => {
      this.num  = 1;
     console.log('this.num = ' + this.num); 
    setTimeout(() => resolve(this.num * 4), 1000)
  });

  let result = await promise; //just assigns resolved value inside executor function into result variable

  console.log(result+'!'); 

}

f();

Since Promise is Thenable then questions are:

-How it works under hood in case when Promise is used with await?

-Does javascript calls then() method of Promise automatically when it meets await?

-Or does javascript distinguish two cases and processes differently in case with Tenable and Promise?

olevacho
  • 23
  • 5
  • Does this article answer your question? https://medium.com/siliconwat/how-javascript-async-await-works-3cab4b7d21da – shidoro Jan 18 '22 at 12:25
  • Yes, `await` just calls `.then()`. It cannot "*just automatically returns resolved value*" if the promise has not yet been resolved, so it waits for it - using the usual `.then(onFulfilled, onRejected)` syntax. – Bergi Jan 18 '22 at 13:10
  • @Bergi just for my own clarification, `await new Thenable(1)` will create a native promise and resolve that native promise to the thenable by passing in the `resolve/reject` of the native promise to the `thenable.then(resolve, reject)`? `then` method is called as a result of resolving the native promise to the thenable?! – Yousaf Jan 18 '22 at 13:13
  • 1
    @Yousaf Yes, `var x = await value; …` basically is `Promise.resolve(value).then(x => …)`. Of course you cannot really observe the native promise that is created only as an intermediate. – Bergi Jan 18 '22 at 13:17

0 Answers0