以下のソースの様に、asyncの関数を即時実行させて、その返り値を取得した時に、Promiseオブジェクトが返却されてしまいます。
非同期メソッド即時実行させたあと、非同期の処理を待ち合わせする方法ってありますでしょうか??
よろしくお願いいたします。
Javascript
1const promiseMethod = (index) => { 2 return new Promise((resolve, { }) => { 3 setTimeout(() => { 4 console.log(index); 5 resolve(index); 6 }, Math.random() * 200); 7 }); 8} 9 10const num = (async () => { 11 let a = [] 12 let result = 0; 13 for (let index = 0; index < 10; index++) { 14 const retValue = await promiseMethod(index); 15 result += retValue; 16 a.push(result) 17 } 18 console.log(a); 19 return a 20})(); 21 22console.log(num) //<-- ここで非同期メソッドの待ち合わせしたい!
terminal
1$ node example/async_test.js 2Promise { <pending> } 30 41 52 63 74 85 96 107 118 129 13[ 0, 1, 3, 6, 10, 15, 21, 28, 36, 45 ]
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。