如何在Tokio中使用async / await语法?

时间:2019-02-24 16:20:44

标签: async-await rust rust-tokio

我正在尝试对Rust中的进程使用异步/等待。我正在使用<script type="text/javascript"> function admissible() { var b = 4; var answer = ''; var elementsList = document.querySelectorAll("#question5"+" input:checked"); //get the selected checkbox values for the missing elements if (elementsList.length >= 0) { //Code works only if some checkbox is checked elementsList.forEach(function(e,q,t){ if ((e.id.indexOf("photo") > -1) || (e.id.indexOf("name") > -1)) { //yes answer = 'yes'; } else { answer = 'no'; } });} else { //display error: you must select a value } console.log(answer); } </script> <div class="questionholder" id="question5"> <div> <h5>Select all elements</h5> <input class="input5" type="checkbox" id="elementName" name="element" value="name"><label for="elementName"><p class="radioChoice">Name</p></label> <input class="input5" type="checkbox" id="elementPhoto" name="element" value="photo"><label for="elementPhoto"><p class="radioChoice">Photo</p></label> <input class="input5" type="checkbox" id="elementSignature" name="element" value="signature"><label for="elementSignature"><p class="radioChoice">Signature</p></label> </div> <div class="holdButtons"> <a class="text2button" onclick="admissible()">Next</a> </div> </div><script type="text/javascript"> function admissible() { var b = 4; var answer = ''; var elementsList = document.querySelectorAll("#question5"+" input:checked"); //get the selected checkbox values for the missing elements if (elementsList.length >= 0) { //Code works only if some checkbox is checked elementsList.forEach(function(e,q,t){ if ((e.id.indexOf("photo") > -1) || (e.id.indexOf("name") > -1)) { //yes answer = 'yes'; } else { answer = 'no'; } });} else { //display error: you must select a value } console.log(answer); } </script>

tokio

这是我得到的错误:

tokio-process

我该如何正确处理?

1 个答案:

答案 0 :(得分:2)

Tokio和相关的板条箱是使用稳定期货0.1条板箱实现的。此板条箱的Future特质在概念上与标准库中的Future特质的版本相似,但细节上有很大不同。 async / await语法是围绕标准库中特征的版本构建的。

在Internet上搜索“ tokio async await”会导致使用恰当命名的板条箱tokio-async-await。本文记录了如何使Tokio能够参与不稳定的期货交易:

[dependencies]
tokio = { version = "0.1.15", features = ["async-await-preview"] }
tokio-process = "0.2.3"

在您的代码中,您必须在针对期货0.1板条箱和标准库的特征实现的Future之间进行转换。一种简单的方法是使用await宏的Tokio版本:

#![feature(await_macro, async_await, futures_api)]

use std::process::Command;
use tokio_process::CommandExt;

fn main() {
    tokio::run_async(main_async());
}

async fn main_async() {
    let out = Command::new("echo")
        .arg("hello")
        .arg("world")
        .output_async();
    let s = tokio::await!(out);
    println!("{:?}", s);
}
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.10s
     Running `target/debug/oo`
Ok(Output { status: ExitStatus(ExitStatus(0)), stdout: "hello world\n", stderr: "" })

经过测试:

  • Rust 1.34.0-每晚(e1c6d0057 2019-02-22)
  • Rust 1.34.0-nightly(aadbc459b 2019-02-23)

另请参阅: