generated at
Promiseで並列に非同期処理を行う
Promise.all()を使う
Promise.all([promise1, promise2,..])
引数はPromiseオブジェクトの配列
引数のPromiseが全てresolveされると、 then が呼び出される


引数のPromiseは並列に実行されている
js
// t ms後にconsole.logを出力するPromiseを返す関数 const p = t => new Promise(resolve => { setTimeout(() => { console.log(`promsie ${t}`); resolve(); }, t); }); const p1 = p(16); const p2 = p(10); const p3 = p(20); const before = new Date(); // allを使う Promise.all([p1, p2, p3]).then(() => { const after = new Date(); const result = after.getTime() - before.getTime(); console.log(result); }).catch(err => { console.error(err); }) // 結果 // promsie 10 // promsie 16 // promsie 20 // 21 ←直列に実行されているなら10+16+20msになるはず
配列の中のいずれかがrejectすると、即座にcatchが返される


then() でvalueを伝搬させると逐次処理になる
valueを伝搬させなければ、並行処理になった(allを使わずとも)
js
const p = t => v => new Promise(resolve => { setTimeout(() => { console.log(`value ${v}`); resolve(`value ${v}`); }, t); }); // ↓これらはvalueを引数に取る関数 const p1 = p(16); const p2 = p(10); const p3 = p(20); const before = new Date(); Promise.resolve() .then(() => p1('value')) .then(v => p2(v)) .then(v => p3(v)) .then(() => { const after = new Date(); const result = after.getTime() - before.getTime(); console.log(result); }) .catch(err => { console.error(err); });