うまくいかないのはPromiseの問題ではなくまさかのforEachの問題だった! forEachのループの中でawaitしても待ってくれません。ぐぬぬ・・・。 for-ofなら大丈夫みたいです。
ダメな例(waitで待たずにループを抜けてしまう)
func3 = async () => { let acc = []; const arr = [1, 2, 3]; arr.forEach(async (v, i) => { let res = await timer(); console.log(res); acc.push(res); }); console.log(acc); };
うまくいく例(配列の順番に実行)
func4 = async () => { let acc = []; const arr = [1, 2, 3]; for (let v of arr) { let res = await timer(); console.log(res); acc.push(res); } console.log(acc); };
並列化する場合
func5 = async () => { let acc = []; const arr = [1, 2, 3]; acc = await Promise.all( arr.map(async (v, i) => { return await timer(); }) ); console.log(acc); };