0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

非同期処理(promise)

Last updated at Posted at 2023-04-09

非同期処理とは

  • Webアプリケーションの中で、ブラウザからサーバーにデータを送信したり、サーバーからデータを受信したりするための仕組みです。

JavaScriptにおいて非同期処理を扱うための手段として、Promiseとawait/asyncがあります。

  • Promiseは、
    • 非同期的な処理を行う関数を実行し、その結果を処理するためのオブジェクトです。Promiseを使用することにより、コールバック関数のような深いネストを回避することができます。

以下は、Promiseを使用した非同期処理の例です。

// Promiseを使用した非同期処理
function fetchData() {
  return new Promise((resolve, reject) => {
    fetch('https://example.com/data')
      .then(response => response.json())
      .then(data => resolve(data))
      .catch(error => reject(error));
  });
}

// fetchData関数を呼び出してデータを取得する
fetchData()
  .then(data => {
    // データを処理する
    console.log(data);
  })
  .catch(error => {
    // エラーを処理する
    console.error(error);
  });

また、Promiseと同様に、await/aysncを使用することもできます。
await/aysncを使用することにより、Promiseをよりシンプルに扱うことができます

awaitは、Promiseが解決されるまで処理を待機するためのキーワードである。
asyncは、非同期処理を行う関数を定義するためのキーワードです。

以下は、await/aysncを使用した非同期処理の例です。

// await/asyncを使用した非同期処理
async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    throw new Error(error);
  }
}

// fetchData関数を呼び出してデータを取得する
async function getData() {
  try {
    const data = await fetchData();
    // データを処理する
    console.log(data);
  } catch (error) {
    // エラーを処理する
    console.error(error);
  }
}

getData();

ここでは、try/catch文を使用することで、エラー処理を簡単に行うことができます。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?