2.1 Promiseの作成
Promiseは、非同期操作の完了(または失敗)とその結果を表すオブジェクトだよ。 ES6 (ECMAScript 2015)で導入されて、JavaScriptの非同期コードを扱う標準的な方法になったんだ。
基本的な概念
Promiseは3つの状態のいずれかにあるよ:
- Pending (保留中): 初期状態、まだ完了も拒否もされていない。
- Fulfilled (成功): 操作が成功したよ。
- Rejected (失敗): 操作がエラーで終了してしまった。
Promiseの作成
PromiseはPromiseコンストラクタを使って作成されるよ。これはexecutor functionを受け取る。 この関数はresolveとrejectという2つの引数を取るんだ。 この関数の中で非同期コードが実行され、成功したらresolveが呼ばれ、 エラーの場合はrejectが呼ばれるんだ。
シンタックス:
const promise = new Promise((resolve, reject) => {
// 非同期操作
if (/* 成功したら */) {
resolve(value); // 成功
} else {
reject(error); // エラー
}
});
Promise作成の例:
JavaScript
const myPromise = new Promise((resolve, reject) => {
const success = true; // 成功の条件
if (success) {
resolve('Operation was successful');
} else {
reject('Operation failed');
}
});
2.2 Promiseの使用
thenメソッド
thenメソッドは、Promiseが成功したときの処理に使われるんだ。成功時の処理用の関数と、エラー処理用の関数の2つを受け取る。 でも、通常はエラー処理にはcatchメソッドを使うよ。
thenの使用例:
JavaScript
myPromise.then(
(successMessage) => {
console.log(successMessage); // 出力されるよ: Operation was successful
},
(errorMessage) => {
console.error(errorMessage); // エラーの時に呼ばれるよ
}
);
catchメソッド
catchメソッドは、Promiseのエラー処理に使われるんだ。Promiseが拒否された場合に呼ばれる1つの関数を受け取る。
catchの使用例:
JavaScript
myPromise
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.error(errorMessage); // 出力される: Operation failed
});
finallyメソッド
finallyメソッドは、Promiseの結果に関係なくコードを実行するために使われるんだ。 引数は取らず、Promiseの完了後、または拒否後に必ず実行されるよ。
finallyの使用例:
JavaScript
myPromise
.then((successMessage) => {
console.log(successMessage);
})
.catch((errorMessage) => {
console.error(errorMessage);
})
.finally(() => {
console.log('Operation completed'); // どっちにしても呼ばれるよ
});
2.3 Promiseの使用例
例 1: Promiseを使った非同期操作
タイマーを使った非同期操作のシミュレーション。
JavaScript
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const success = Math.random() > 0.5;
if (success) {
resolve('Async operation was successful');
} else {
reject('Async operation failed');
}
}, 2000);
});
}
asyncOperation()
.then((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log('Async operation completed');
});
例 2: Promiseの連続実行
連続した非同期操作のシミュレーション。
JavaScript
function firstOperation() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('First operation completed');
resolve('First result');
}, 1000);
});
}
function secondOperation(result) {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Second operation completed');
resolve(`Second result, received: ${result}`);
}, 1000);
});
}
firstOperation()
.then((result) => {
return secondOperation(result);
})
.then((finalResult) => {
console.log(finalResult);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log('Both operations completed');
});
例 3: Promise.allを使った並行実行
並行した非同期操作のシミュレーション。
JavaScript
function operationOne() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Operation One completed');
resolve('Result One');
}, 1000);
});
}
function operationTwo() {
return new Promise((resolve) => {
setTimeout(() => {
console.log('Operation Two completed');
resolve('Result Two');
}, 1500);
});
}
Promise.all([operationOne(), operationTwo()])
.then((results) => {
console.log('All operations completed');
console.log(results); // 出力される: ['Result One', 'Result Two']
})
.catch((error) => {
console.error('One of the operations failed', error);
});
GO TO FULL VERSION