LoginSignup
0
0

More than 1 year has passed since last update.

非同期タスク(複数)を同期的に実行

Last updated at Posted at 2022-04-19

こんにちは。
非同期タスク(複数)を、同期的に(順に)実行させました。すなわち、

  • 非同期タスク関数を、new Promise()を戻り値とする形に仕立て、
  • その実行完了(resolve() が返される)を待った後に(=await)、次(の行)の関数が実行されます1

実行例およびソース

下記のwaitTimes = [600, 400, 200] で与えた順序に従って同期的実行します。

image
promise.html
<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8>
</head>
<body>
  <div id='debug' style='padding:4px;background-color:#fffc;position:absolute;left:0;top:0;color:#0af;font-family:courier;font-size:12px;user-select:none'></div>
</body>
<script>
const strArrayDebug = [];
const waitTimes = [600, 400, 200];

(async () => {
  for (const waitTime of waitTimes) {
    await funcWait(waitTime);
    showDebugPush(`waited for ${waitTime}ms. (later)`);
  }
  showDebugPush("done.");
})();

function funcWait(waitTime) {
  const func_wait = (resolve) => {
    setTimeout(() => {
      resolve();
      showDebugPush(`waited for ${waitTime}ms. (earlier)`);
    }, waitTime);
  };
  return new Promise(func_wait);
}

function showDebugPush(str) {
  strArrayDebug.push(str);
  document.getElementById("debug").innerText = strArrayDebug.join("\n");
}
</script>
</html>
  1. 同期的実行は不要な場合にはPromise.all()を用いることができます。複数の関数の指定順序順通りの実行結果配列を得られます。

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