Issue
I read this portion of the book on Async programming in Rust https://rust-lang.github.io/async-book/03_async_await/01_chapter.html
I see the mention of the .await syntax,
and then I later saw a blog where reqwest is being used to fetch a url. The code looks like this:
let resp200 = client.get("https://httpbin.org/ip")
.header(CONTENT_TYPE, "application/json")
.send()
.await?
.json::<GETAPIResponse>()
.await?;
I do not understand the .await?. I know ? is a shorthand for extracting the Ok case or returning from the function with an Error. But as far as I am aware, .await does not return Result so how is it possible to do .await with ?
Solution
.await simply turns a impl Future<Output = T> into a T.
? (mostly) turns a Result<T, E> into a T.
When put together, .await? turns a impl Future<Output = Result<T, E>> into a T.
The following code is equivalent:
let future = client.get("https://httpbin.org/ip")
.header(CONTENT_TYPE, "application/json")
.send();
let result: Result<_, _> = future.await;
let response: Response = result?;
let json_future = response.json();
let json_response: Result<_, _> = json_future.await;
let json = json_response?;
But, .await? is not a special operator. It's literally just .await followed by ?
Answered By - cameron1024 Answer Checked By - Cary Denson (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.