LoginSignup
1
4

More than 3 years have passed since last update.

【JavaScript修行】promiseループですごい詰まった

Last updated at Posted at 2019-07-29

何に詰まったかというと、forループ内でプロミスを回そうとして全然上手くいかなかったんです。

function(){
   for(let i=0,i<DATA_DAYS;i++){
      fetch(~~)
      .then(res=>
     //~~~省略~~~

これじゃ上手く行きませんよね。
全部のforが回ってから動かす、っていうのがどうも難しくて悪戦苦闘。そしてこの記事を見つけました。

https://qiita.com/progre/items/5666f4a333cc2d032d15
まさに探していた内容が!
forでとった1つ1つのプロミスをPromise.allを使って
確認するというものです。

var promises = [];
for (var i = 0; i < takusan; i++) {
    promises.push(omotaiPromise(i));
}
Promise.all(promises)
    .then(function (results) {
        // results配列の各要素で結果が取れる
    });

これを参考にしつつ、見事抜き出したかった配列を作ることができました。

完成
let promises = [];
for(let i=0;i<DATA_DAYS;i++){
  promises[i]=
    fetches.fetchNHK(i)
    .then(res=>{
      count[i] = res.list.e1.length;
      day[i] = moment(i,'days').format('MM月DD日');
    })
}

Promise.all(promises)
.then(res =>{
// 以下配列を使った処理
}

すごいぜ!

追記 async/awaitでかく

async/awaitでかくとかなりにスッキリとしたコードになりました。

async/await
async function forFethches(){
  for(let i=0;i<DATA_DAYS;i++){
      await fetches.fetchNHK(i)
      .then(res=>{
        count[i] = res.list.e1.length;
        day[i] = moment(i,'days').format('MM月DD日');
      })
  }
}

forFethches()
.then(res =>{
   //配列に対しての処理
})

async/awaitも使いこなせるようにならないとな、と思いました。
@megmism さんありがとうございました!

1
4
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4