LoginSignup
0
0

JavaScriptのPromiseとは何か?

Last updated at Posted at 2024-06-24

JavaScriptのPromiseを一言で説明すると?

非同期処理の結果を扱うためのオブジェクト。

JavaScriptのPromiseの何が良いのか?

非同期処理をよりシンプルで直感的に記述できるようにし、可読性を向上させる。

Promiseを利用しない例

function asyncTask(callback) {
    setTimeout(() => {
        const result = "成功";
        console.log("非同期処理の完了");
        callback(result); // 5秒後に実行
    }, 5000);
}

function callbackTask(result) {
    console.log("コールバック処理を実行");
    console.log("非同期処理の結果:", result);
}

asyncTask(callbackTask);

Promiseを利用する例

const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        const result = "成功";
        console.log("非同期処理の完了");
        resolve(result); // 5秒後に実行
    }, 5000);
});

promise.then((result) => {
    console.log("コールバック処理を実行");
    console.log("非同期処理の結果:", result);
});

async/awaitを利用してコールバック関数を使わない例

async function runAsyncTask() {
    const promise = new Promise((resolve, reject) => {
        setTimeout(() => {
            const result = "成功";
            console.log("非同期処理の完了");
            resolve(result); // 5秒後に実行
        }, 5000);
    });

    const result = await promise;
    console.log("非同期処理の結果:", result);
}

runAsyncTask();
0
0
4

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