LoginSignup
8
4

More than 3 years have passed since last update.

JavaScript: Promise.raceの基本的な使い方

Last updated at Posted at 2020-08-03

Promise.raceは2つ以上のPromiseのどちらか早い方を戻り値として取得する関数です。

下の例では、100ミリ秒後に完了するPromiseと、200ミリ秒後に完了するPromiseのどちらか早く完了するほうを取得するものです。この例では、前者のほうが早いので、Promise.raceで得られる値はPromise<"100ミリ後に完了した処理">のほうになります。

async function test1() {
  // 100ミリ後に完了する処理
  const one = new Promise(resolve =>
    setTimeout(() => resolve('100ミリ後に完了した処理'), 100),
  )

  // 200ミリ秒後に完了する処理
  const two = new Promise(resolve =>
    setTimeout(() => resolve('200ミリ後に完了した処理'), 200),
  )

  const result = await Promise.race([one, two])
  console.log(result)
  //=> "100ミリ後に完了した処理"
}

test1()
8
4
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
8
4