task_race

task_race

task_race

Function

Waits for the first of a set of background tasks to complete and returns its result. task_race(tasks) Use task completion subscription wake-up instead of polling through done() plus sleep().

Syntax

Parameters

ParametersTypeRequiredDefault valueDescription
tasksArrayYesNoneAn array of Tasks to compete for completion results.

Return value

TypeDescription
Any value / EmptyReturns the result of the first completed task; an empty array returns empty.

If the winning task throw, task_race() will be re-thrown; if the winning task fails normally, a runtime error will be returned. Other unfinished tasks will continue to run and will not be forcibly canceled.

Example

Notes

  • The parameter must be an array, and all array elements must be Task.
  • When a task has been completed before registration, the first completed task will be returned in the order entered.
  • When multiple tasks are completed almost at the same time, they will be returned in the order in which the completion events enter the waiting channel; completed scans in the same round will break the tie in the order of input.
  • When the same Task appears multiple times in the array, it will be considered as multiple candidates based on the input position.
  • task_race() blocks the current execution flow; should be used with caution in web request hot paths.