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 1 year has passed since last update.

node js - 複数の同時並行処理をしてPromiseの結果を待ち受ける (Promiseの変数代入とawait)

Last updated at Posted at 2022-11-03

コード

3秒程度かかる処理を同時並行で複数実行する
戻り値でPromiseを得ておいて後からPromiseに対してawaitする

const { setTimeout } = require('timers/promises');

const long_tasks = async () => {
  long_task_promise1 = long_task();
  long_task_promise2 = long_task();
  long_task_promise3 = long_task();

  long_task_var1 = await long_task_promise1;
  long_task_var2 = await long_task_promise2;
  long_task_var3 = await long_task_promise3;

  console.log(long_task_var1);
  console.log(long_task_var2);
  console.log(long_task_var3);
};

const long_task = async () => {
  await setTimeout(3000);
  return "long task";
};

long_tasks();

結果

すべての処理が3秒程度で終わり結果が表示される

long task
long task
long task

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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?