The async/await syntax

Some programming languages, such as JavaScript and C#, have async and await operators which help to write asynchronous code that looks like synchronous code. The nightly version of the Rust compiler supports a new syntax and adds async and await (actually, this is a macro) keywords to the language to simplify the writing of asynchronous applications. The new code might look as follows:

async fn http_get(addr: &str) -> Result<String, std::io::Error> {
let mut conn = await!(NetwrokStream::connect(addr))?;
let _ = await!(conn.write_all(b"GET / HTTP/1.0 "))?;
let mut buf = vec![0;1024];
let len = await!(conn.read(&mut buf))?;
let res = String::from_utf8_lossy(&buf[..len]).to_string();
Ok(res)
}

This is not stable yet and may be changed before release. async is a new keyword that converts a standard function to asynchronous. await! is a macro that is built in in unstable Rust versions. It suspends the execution of a function and waits for the result from a Future instance provided to await! as argument. This macro uses the generators feature to interrupt execution until the Future under await! has been completed.

In the remaining part of this chapter, we are going to look at a proxy that uses streams to process incoming and outgoing data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.163.197