async_macros/
join.rs

1#![allow(non_snake_case)]
2
3/// Awaits multiple futures simultaneously, returning all results once complete.
4///
5/// While `join!(a, b)` is similar to `(a.await, b.await)`,
6/// `join!` polls both futures concurrently and therefore is more efficent.
7///
8/// This macro is only usable inside of async functions, closures, and blocks.
9///
10/// # Examples
11///
12/// ```
13/// #![feature(async_await)]
14/// # futures::executor::block_on(async {
15/// use async_macros::join;
16/// use futures::future;
17///
18/// let a = future::ready(1u8);
19/// let b = future::ready(2u8);
20///
21/// assert_eq!(join!(a, b).await, (1, 2));
22/// # });
23/// ```
24#[macro_export]
25macro_rules! join {
26    ($($fut:ident),* $(,)?) => { {
27        async {
28            $(
29                // Move future into a local so that it is pinned in one place and
30                // is no longer accessible by the end user.
31                let mut $fut = $crate::MaybeDone::new($fut);
32            )*
33            $crate::utils::poll_fn(move |cx| {
34                use $crate::utils::future::Future;
35                use $crate::utils::task::Poll;
36                use $crate::utils::pin::Pin;
37
38                let mut all_done = true;
39                $(
40                    let fut = unsafe { Pin::new_unchecked(&mut $fut) };
41                    all_done &= Future::poll(fut, cx).is_ready();
42                )*
43                if all_done {
44                    Poll::Ready(($(
45                        unsafe { Pin::new_unchecked(&mut $fut) }.take().unwrap(),
46                    )*))
47                } else {
48                    Poll::Pending
49                }
50            }).await
51        }
52    } }
53}