Open1

Promises must be awaited, end with a call to エラーの解決方法

まさぴょん🐱まさぴょん🐱

Promises must be awaited, end with a call to エラー

エラー原因

  • Promiseの終了のさせ方に関するESLintエラー
Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator

解決方法

1. awaitを使用する

非同期関数を呼び出すときにawaitを使います。

async function fetchData() {
    const data = await fetch('https://example.com/api/data');
    console.log(data);
}

2. catchを使用する

.catchメソッドを使ってPromiseのエラーを処理します。

fetch('https://example.com/api/data')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));

3. thenの中でエラー処理を行う

.thenの第二引数としてエラーハンドラを渡します。

fetch('https://example.com/api/data')
    .then(response => response.json(), error => console.error('Error:', error))
    .then(data => console.log(data));

4. void演算子を使用する

特定のPromiseを無視する場合にはvoidを使います。

void fetch('https://example.com/api/data');