Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utility for polling a future from an async function #2257

Closed
Plecra opened this issue Nov 5, 2020 · 3 comments · Fixed by #2452
Closed

Utility for polling a future from an async function #2257

Plecra opened this issue Nov 5, 2020 · 3 comments · Fixed by #2452
Labels
A-future Area: futures::future C-feature-request

Comments

@Plecra
Copy link

Plecra commented Nov 5, 2020

struct Check<'a, F: Future + ?Sized>(Pin<&'a mut F>);
impl<F: Future + ?Sized> Future for Check<'_, F> {
    type Output = Poll<F::Output>;
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
        Poll::Ready(self.0.as_mut().poll(cx))
    }
}
async fn checkup(tasks: Vec<Task>) {
    for mut task in tasks {
        if let Poll::Ready(val) = Check(task.fut.as_mut()).await {
            handle(val);
            cleanup(task);
        }
    }
}

I've seen this pattern come up in a few different projects now, and it seems generic enough for the futures crate. It could well be too niche though.

@taiki-e
Copy link
Member

taiki-e commented Nov 7, 2020

This seems similar to use now_or_never on (pinned) reference. (in this case, task.fut.as_mut().now_or_never())

@Plecra
Copy link
Author

Plecra commented Nov 7, 2020

It does look similar ☺️ The difference is that Check may be used multiple times, due to it being implemented on a pinned reference (now_or_never is implemented for all T: Future).

@taiki-e
Copy link
Member

taiki-e commented Nov 7, 2020

The difference is that Check may be used multiple times, due to it being implemented on a pinned reference (now_or_never is implemented for all T: Future).

Pinned future implements Future, so I don't think this difference is a problem.

The actual difference is the context passed to the future. (now_or_never pass no-op context.)
See also #1747 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-future Area: futures::future C-feature-request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants