一部正しくない内容があったので修正して再回答します。
Promise
の引数p
、then
メソッドの引数t
、catch
メソッドの引数c
はどれも関数オブジェクトで、関数は未実行です。
new Promise(p)
でPromise
を作りpending
状態にして関数p
を呼び出します。
関数p
に渡されたresolve(値)
を呼び出すとPromise
に値が設定されfulfilled
状態になり、関数t
を呼ぶ準備ができた状態になります。
関数p
に渡されたreject(値)
を呼び出すとPromise
に値が設定されreject
状態になり、関数c
を呼ぶ準備ができた状態になります。
Promise.all
や Promise.race
はPromice
を作るだけで何も呼び出しません。
スクリプトをすべて実行し終わってJavaScript実行エンジンに制御が戻ると、Promice
の状態に応じて関数t
や関数c
を呼び出します。
all
は、リストのすべてのPromise
が完了状態になるとall
の関数t
が呼び出されます。
race
は、リストのいずれかのPromise
が完了した時点でrace
の関数t
が呼び出されるので、all
よりも先にrace
の結果が表示されることになります。
試しに、ソースコードの最後で require('process').exit();
を実行するようにしてJavaScript実行エンジンNode.jsで実行してみると、JavaScript実行エンジンに制御が戻らずにプログラムが終了するため、Promise
のthen
やcatch
が呼び出されないことが確認できます。
console.log("start")
function callResolve(resolve, reject) {
console.log('called callResolve');
resolve("resolveなんだ");
}
function callReject(resolve, reject) {
console.log('called callReject');
reject("rejectなんだ");
}
function calledThen(resolve, reject) {
console.log('called calledThen');
}
function calledCatch(resolve, reject) {
console.log('called calledCatch');
}
function printValue(val) {
console.log(val);
}
function doneAll() {
console.log("全Promise終了");
}
function doneRace() {
console.log("あるPromise終了");
}
const promise1 = new Promise(callReject).then(calledThen).catch(printValue);
console.log('promise1');
const promise2 = new Promise(callResolve).then(printValue).catch(calledCatch);
console.log('promise2');
Promise.all([promise1, promise2]).then(doneAll);
console.log('promise3');
Promise.race([promise1, promise2]).then(doneRace);
console.log('promise4');
// require('process').exit();
console.log("end")
実行結果
start
called callReject
promise1
called callResolve
promise2
promise3
promise4
end
resolveなんだ
rejectなんだ
あるPromise終了
全Promise終了
exitした場合
start
called callReject
promise1
called callResolve
promise2
promise3
promise4