LoginSignup
0
0

More than 3 years have passed since last update.

forEach だと await が効かない

Posted at

はじめに

以前制作したアプリケーションの実装中にハマってしまった解決策のメモです。
いつか使うだろうと言うことで書いておきます。

結論

for of を使って実装しましょう

const texts = [...];
for (const text of texts) {
    const fetchData = await fetch(...);
    fetchDataArray.push(fetchData);
}

データを取得して直列的に待ちながら処理をしようとしたら…

いつもの感覚で forEach を使って実装したらうまく動きませんでした…

const texts = [...];
texts.forEach((e) => {
    const fetchData = await fetch(...);
    fetchDataArray.push(fetchData);
});

どうやら forEach は Promise を無視して動作するようです。
なので for of を使ってループしてあげる必要があるみたいですね。

const texts = [...];
for (const text of texts) {
    const fetchData = await fetch(...);
    fetchDataArray.push(fetchData);
}

このように書けば問題なく動作すると思われます。

余談

実は、Promise.all の使い方をよく理解できてません。今回みたいな使い方でも同じ動作できるように実装できるのかなあ?
今後改めて勉強したいと思います 😢

0
0
2

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
0
0