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.