Implement Future "async waiting of specific response/body from reqwest"

I want to implement Future (async function), which will wait specific body's response from reqwest's GET request.

I start to implement it, using futures crate for chaining async functions in poll function of the Future trait, but it looks terrible and complicated:

struct RequestFuture {
    request: String,
    response: Option<Result<JsonValue>>,
}

impl Future for RequestFuture {
    type Output = Result<JsonValue>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let future = self.get_mut();
        match future.response.take() {
            Some(response) => match response {
                Ok(json_value) => {
                    // Return Poll::Pending, if `json_value` doesn't have needed fields.
                    todo!()
                }
                Err(err) => Poll::Ready(Err(err)),
            },
            None => {
                let future_request = Box::pin(reqwest::get(&self.request).then(|r| match r {
                    Ok(r) => r.json(), // Mismatched types
                    Err(err) => async { err }, // Mismatched types
                }));
                future_request.as_mut().poll(cx)
            }
        }
    }
}

I wanted to ask you, am I going in the right direction or can this be implemented in more idiomatic style and more simply?

P.S. Also, I don't know yet which waker should I call.

Implementing things using a poll function is hard-mode async Rust. I would not recommend it, instead I would go for writing an async function that does what you want.

My main problem was getting status of correct body of response (à la waker function). So I have not found any solution other than persistent connection with using backoff crate.

@alice, thanks again. I constantly don't see easy solutions to a problem. In summary, I wrote async function.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.