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?