JavaScriptのPromiseとは?非同期処理をわかりやすく管理する方法
JavaScriptの非同期処理を扱ううえで欠かせないのが「Promise(プロミス)」です。
コールバック関数のネスト地獄を避け、より見通しの良いコードを書くための仕組みとして導入されました。
この記事では、Promiseの基本的な使い方から、実践的な活用方法までをわかりやすく解説します。
Promiseとは?
Promiseとは、非同期処理の「結果」を表すオブジェクトです。
今はまだ終わっていないけれど、将来的に「成功する」か「失敗する」かのどちらかになることを約束(promise)します。
Promiseの基本構文
const promise = new Promise(function(resolve, reject) {
// 非同期処理
if (成功した場合) {
resolve(結果);
} else {
reject(エラー);
}
});
resolve
は処理が成功したときに呼び出し、reject
は失敗したときに呼び出します。
thenで成功時の処理を記述
const promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve("成功しました");
}, 1000);
});
promise.then(function(result) {
console.log(result); // 成功しました
});
then
は、Promiseが成功(resolve)されたときに呼び出されます。
catchでエラー処理を記述
const promise = new Promise(function(resolve, reject) {
setTimeout(function() {
reject("エラーが発生しました");
}, 1000);
});
promise
.then(function(result) {
console.log(result);
})
.catch(function(error) {
console.log(error); // エラーが発生しました
});
catch
は、Promiseが失敗(reject)されたときに実行されます。
Promiseの状態(ステート)
Promiseには3つの状態があります。
- pending(保留):まだ処理中
- fulfilled(成功):
resolve()
が呼ばれた状態
- rejected(失敗):
reject()
が呼ばれた状態
Promiseチェーン
then
を連続して書くことで、処理を順番につなげることができます。
new Promise(function(resolve) {
resolve(1);
})
.then(function(result) {
console.log(result); // 1
return result + 1;
})
.then(function(result) {
console.log(result); // 2
return result + 1;
});
Promise.allとPromise.race
複数のPromiseを同時に処理したい場合は、Promise.all
や Promise.race
が便利です。
Promise.all
Promise.all([
Promise.resolve("A"),
Promise.resolve("B")
]).then(function(results) {
console.log(results); // ["A", "B"]
});
Promise.race
Promise.race([
Promise.resolve("A"),
Promise.resolve("B")
]).then(function(result) {
console.log(result); // 最初に終わったもの("A")
});
まとめ
- Promiseは非同期処理の結果を表すオブジェクト
then
で成功時、catch
で失敗時の処理を記述
- 状態には pending / fulfilled / rejected の3つがある
- Promiseチェーンで複数の処理を順番に実行できる
Promise.all
や Promise.race
で複数のPromiseをまとめて処理できる
PromiseはJavaScriptの非同期処理を効率的に扱うための基本ツールです。
コールバック関数よりも見やすく、エラー処理もしやすくなるため、ぜひ使い方をマスターしておきましょう。