2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

同期処理、非同期処理とは

Last updated at Posted at 2025-04-09

JavaScriptを勉強中の初心者です。今回は「非同期処理」について学んだことを、自分の理解の整理も兼ねてまとめてみます。


🔍 この記事でわかること

  • 同期処理と非同期処理の違い
  • JavaScriptでの非同期処理の書き方(async/await, .then)

✅ 同期処理と非同期処理の違い

:point_up: 同期処理

処理が上から順番に実行される処理方法。
ひとつが終わるまで、次の処理に進めません。

console.log("タスクAを実行");
console.log("タスクBを実行");
console.log("タスクCを実行");

出力

タスクAを実行
タスクBを実行
タスクCを実行

:point_up: 非同期処理

時間がかかる処理(通信やタイマーなど)を待たずに進める処理方法。
時間のかかる処理を裏で行いながら、他の処理を進めるイメージ。

console.log("タスクAを実行");

setTimeout(()=> {
    console.log("タスクBを実行, (3秒後)");
},3000);

console.log("タスクCを実行");

出力

タスクAを実行
タスクCを実行
タスクBを実行, (3秒後)

✅ JavaScriptでの非同期処理の書き方(async/await, .then)

:point_up: 非同期処理の書き方①:async / await

const resultTaskB = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("タスクBを実行");
    }, 2000);
  });
};

const sampleFunction = async () => {
  console.log("1.タスクAを実行");
  
  const result = await resultTaskB();
  console.log("2." + result);
  
  console.log("3.タスクCを実行");
};

sampleFunction();

出力

1.タスクAを実行
2.タスクBを実行
3.タスクCを実行

resultTaskBの処理をawaitで待ちますが、asyncの外側の処理は進めます。

:point_up: 非同期処理の書き方②:.then でつなげる

const resultTaskB = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve("タスクBを実行");
    }, 2000);
  });
};

console.log("1.タスクAを実行");

resultTaskB()
  .then((result) => {
    console.log("2." + result);
    console.log("3.タスクCを実行");
  });

出力

1.タスクAを実行
2.タスクBを実行
3.タスクCを実行

Promiseを返す関数のあとに.then()を使って処理を続けます。


他にも「Promiseを省略する場合」、「Promise.allで多数の処理を待つ場合」などありますが、別で記事にしたいと思います。

参考にしたサイト:https://jsprimer.net/basic/async/

2
3
2

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?