LoginSignup
0
0

More than 1 year has passed since last update.

配列型ループ(forEach)+ await

Last updated at Posted at 2021-06-16

こんにちは。
配列型オブジェクト(下記)に対して指定関数のforEachループ実行を行いました1

  • 配列(array)
  • 配列型(array-like)
  • 反復可能型(iterable)
[...array_like].forEach(doFunc);
Array.from(array_like).forEach(doFunc);
for (const e of array_like) {doFunc(e)};

await 動作としたい場合

ただしループ内で個々をawait動作としたい場合は下記のようにするとのことです2forEachは使わずに)。

  • reduce利用
  • for ( of )利用
array_like.reduce(async (p, e) => {
  await p || await wait();
  doFunc(e);
}, 0);

(async () => {
  for (const e of array_like) {
    await wait();
    doFunc(e);
  }
})();

// const wait = () => new Promise(resolve => setTimeout(resolve, 0));

  1. \ forEachは配列を対象としますので、そうではない配列型オブジェクトに対しては、array_like.forEach(doFunc)とは書けません。 

  2. 参考:「async/awaitを、Array.prototype.forEachで使う際の注意点、という話」 

0
0
0

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