If await gets a "thenable" object, it calls .then() and waits for the resolved value.
replit๏ผawait thenable
// -----------------------------
// โญ "thenable" objects
// -----------------------------
// those with a `.then()` method
class FutureValue {
constructor(value, seconds) {
this.value = value;
this.seconds = seconds;
}
// ๐ธ then()
then(resolve, reject) {
console.log(new Date(), `then() method called`);
setTimeout(resolve, this.seconds * 1000, this.value);
}
}
// โญ normal Promise
function futureValue(value, seconds) {
console.log(new Date(), `futureValue('${value}', ${seconds})`)
return new Promise(resolve => {
setTimeout(resolve, seconds * 1000, value);
});
};
// main
(async () => {
let result = await new FutureValue('hello', 2); // await "thenable" โญ
console.log(new Date(), result);
})();
(async () => {
let result = await futureValue('there', 2); // await Promise
console.log(new Date(), result);
})();
// outcomes:
// -----------------------------------------------
// 2022-08-31T05:04:45.193Z futureValue('there', 2)
// 2022-08-31T05:04:45.197Z then() method called
// 2022-08-31T05:04:47.198Z there
// 2022-08-31T05:04:47.198Z hello