Quirrel4.41.0

async.Future.race

Method of Future, from module "async"
race([arr]): any

Settles as whichever future in arr settles first, fulfilled or faulted.

examples/async/future/race-basic.nut
from "async" import Future

async function main() {
  let scout = Future()
  let medic = Future()
  scout.resolve("scout")   // already settled; medic never does
  println("await Future.race([scout, medic]) =", await Future.race([scout, medic]))
}
main()
Output:
await Future.race([scout, medic]) = scout

Parameters

arranyarray of futures (or plain values) to wait on optional

Return value

A fresh Future. The first input to fulfil fulfils it with that value; the first input to fault faults it with that value - a fault wins the same way a fulfilment does, whichever happens first. Every losing input is discarded with no unhandled-fault report, since race itself read it.

Errors

Throws Future.race: expected an array when arr is not an array, including when it is omitted, and Future.race: empty array for an empty one - checked on the calling frame, so a plain try/catch catches both without await. This differs from JS Promise.race, where an empty array returns a future that never settles; here that shape is treated as a bug and reported at the call site instead.

Notes

When several inputs are already settled before race runs, the earliest one in array order wins (matching JS Promise.race reaction order). A plain value that is not a Future settles immediately - the same pass-through behavior await gives it elsewhere - so it wins over a still-pending future input even when listed after it in arr.

Example

examples/async/future/race.nut
from "async" import Future

async function main() {
  // `loser` is array-first but never settles, so the winner is decided by
  // settle order, not array order.
  let winner = Future(); let loser = Future()
  winner.resolve("first")
  print($"fulfil: {await Future.race([loser, winner])}\n")

  let bad = Future(); let pending = Future()
  bad.reject("boom")
  try { await Future.race([pending, bad]) }
  catch (e) { print($"fault: {e}\n") }
}
main()
Output:
fulfil: first
fault: boom

See also

allRuns every future in arr concurrently and fulfils with an array of their values, in input order, once every one of them fulfils.
Futureclass index