1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【JavaScript】同期処理・非同期処理

Posted at

同期処理(Synchronous Processing)

  • 処理が順番に実行される
  • 前の処理が終わるまで次の処理は始まらない
  • シンプルだけど、重い処理があると全体が止まる(=待ち時間が発生)
// 例)
console.log("1: 処理開始");

for (let i = 0; i < 1000000000; i++) {
  // 時間がかかるループ
}

console.log("2: 処理終了");

1: 処理開始
(ループが終わるまで待つ)
2:処理終了

ループが終わるまでプログラムが完全に停止する

非同期処理(Asynchronous Processing)

  • 処理を並行して進められる
  • すぐに終わらない処理(API通信・ファイル読み込みなど)を待っている間に、他の処理を進められる
  • 効率が良いが、順番通りに動かないことがあるので注意

APIからのデータ取得やファイル読み込みなどで必要

// 例) setTimeout を使った非同期処理
console.log("1: 処理開始");

setTimeout(() => {
  console.log("2: 2秒後の処理");
}, 2000);

console.log("3: 処理終了");

1: 処理開始
3: 処理終了
(2秒後)
2: 2秒後の処理

非同期処理の書き方

代表的なのは コールバック、Promise、async/await の3つ。

①コールバック関数

function asyncProcess(callback) {
  setTimeout(() => {
    console.log("2: 非同期処理");
    callback();
  }, 2000);
}

console.log("1: 処理開始");
asyncProcess(() => {
  console.log("3: コールバック処理");
});

⚠️問題点
➡️ 「ネストが深くなる(コールバック地獄)」 = 可読性が悪くなる

②Promise(プロミス)

非同期処理を扱うためのオブジェクト。
3つの状態(ステータス)を持つ

  • pending(待機中)
    • 初期状態。まだ処理が終わっていない
  • fulfilled(成功)
    • 非同期処理が 成功 して resolve() が呼ばれた状態
  • rejected(失敗)
    • 非同期処理が 失敗 して reject() が呼ばれた状態
function asyncProcess(success = true) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      console.log("2: 非同期処理");
      if (success) {
        resolve("データ取得成功");
      } else {
        reject("エラー発生");
      }
    }, 2000);
  });
}

console.log("1: 処理開始");

asyncProcess(true)
  .then((result) => {
    console.log("3: Promiseの処理");
    console.log(result);
  })
  .catch((error) => {
    console.error("エラー発生:", error);
  });

.then() で成功時の処理、.catch() でエラー処理

✅ポイント

  • .then() を使って処理をつなげる
  • コールバックよりも見やすい

③async/await(最もシンプルなやり方)

function asyncProcess() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log("2: 非同期処理");
      resolve();
    }, 2000);
  });
}

async function main() {
  console.log("1: 処理開始");
  await asyncProcess();
  console.log("3: async/await の処理");
}

main();

Promise と async/await の違い

Promise async/await
書き方 .then() と .catch() を使う async 関数の中で await を使う
可読性 チェーンが長くなると見づらい 同期処理のように書けるので見やすい
エラーハンドリング .catch() を使う try/catch を使う
ネスト .then() をつなげると深くなりがち シンプルでネストが少ない
柔軟性 Promise チェーンを使って処理をつなげられる await を使うと順番に処理できる

参考

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?