# await "thenable"

[JS](https://lochiwei.gitbook.io/web/js) ⟩ [asynchronous](https://lochiwei.gitbook.io/web/js/async) ⟩ [await](https://lochiwei.gitbook.io/web/js/async/await) ⟩ thenable

{% hint style="success" %}
"<mark style="color:purple;">**thenable**</mark>" objects： those with a <mark style="color:blue;">`.then()`</mark> method.
{% endhint %}

{% tabs %}
{% tab title="⭐️ 重點" %}
{% hint style="info" %}
If [](https://lochiwei.gitbook.io/web/js/async/await "mention") gets a "<mark style="color:purple;">**thenable**</mark>" object, it calls <mark style="color:blue;">**.then()**</mark> and waits for the resolved value.
{% endhint %}
{% endtab %}

{% tab title="💈範例" %}
:floppy\_disk: replit：[await thenable](https://replit.com/@pegasusroe/await-thenable#index.js)

```javascript
// -----------------------------
//     ⭐ "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
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] JS.info ⟩ [async / await](https://javascript.info/async-await)
  {% endtab %}
  {% endtabs %}
