ps_promise/methods/
race.rs1use std::{future::Future, pin::pin, task::Poll};
2
3use crate::{Promise, PromiseRejection};
4
5impl<T, E> Promise<T, E>
6where
7 T: Send + Unpin + 'static,
8 E: PromiseRejection,
9{
10 pub fn race<I>(promises: I) -> Self
11 where
12 I: IntoIterator<Item = Self>,
13 {
14 Self::new(PromiseRace::from(promises))
15 }
16}
17
18impl<T, E> Future for PromiseRace<T, E>
19where
20 T: Send + Unpin + 'static,
21 E: PromiseRejection,
22{
23 type Output = Result<T, E>;
24
25 fn poll(
26 self: std::pin::Pin<&mut Self>,
27 cx: &mut std::task::Context<'_>,
28 ) -> std::task::Poll<Self::Output> {
29 let this = self.get_mut();
30
31 for promise in &mut this.promises {
32 if let Poll::Ready(result) = pin!(promise).poll(cx) {
33 return Poll::Ready(result);
34 }
35 }
36
37 Poll::Pending
38 }
39}
40
41pub struct PromiseRace<T, E>
42where
43 T: Send + Unpin + 'static,
44 E: PromiseRejection,
45{
46 promises: Vec<Promise<T, E>>,
47}
48
49impl<I, T, E> From<I> for PromiseRace<T, E>
50where
51 T: Send + Unpin + 'static,
52 E: PromiseRejection,
53 I: IntoIterator<Item = Promise<T, E>>,
54{
55 fn from(value: I) -> Self {
56 Self {
57 promises: value.into_iter().collect(),
58 }
59 }
60}