0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

順不同な非同期処理を待機して順番どおりに実行する

Posted at

非同期処理を呼び出された順番どおりに実行するパターンです。processing変数によって、実行時にフラグをたてておいて、それをsetIntervalで監視してよいタイミングになるとsetIntervalを止めて実行します。

非同期処理をそのまま実行する例

index1.js
const data = ['a', 'b', 'c', 'd', 'e'];

const randomInt = function(min, max) {
  return Math.floor( Math.random() * (max + 1 - min) ) + min;
};
const process = name => {
  setTimeout(() => {
    console.log('process:' + name);
  }, randomInt(1000, 3000));
}

data.forEach((value) => {
  process(value)
  console.log(value);
})

// 実行結果
// a
// b
// c
// d
// e
// process:e
// process:d
// process:b
// process:a
// process:c

順不同な非同期処理を待機して順番どおりに実行する例

index2.js
const data = ['a', 'b', 'c', 'd', 'e'];

const randomInt = function(min, max) {
  return Math.floor( Math.random() * (max + 1 - min) ) + min;
};

let processing = false;
const process = name => {
  processing = true;
  setTimeout(() => {
    console.log('process:' + name);
    processing = false;
  }, randomInt(1000, 3000));
}

data.forEach((value) => {
  const intervalId = setInterval(() => {
    if (processing === true) {
      return;
    }
    clearInterval(intervalId);
    process(value);
  }, 50);
  console.log(value);
})

// 実行結果
// a
// b
// c
// d
// e
// process:a
// process:b
// process:c
// process:d
// process:e
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?