Async-std: how to read two files, non blocking?

I have two files and async fns that read them and produce some structs which I then need to use in another function. Fairly common task to read them so that they do not block each other?
I can spawn and later block-on .await simple examples that do not produce anything but am having trouble passing any useful values out of them for later use. Even with async move. What is the trick?

I mean I can use the structs within the same block
task::block_on(async { ...});
but not across
t1 = task::spawn(async move { ... });
t2 = task::spawn(async move { ... });
task::block_on(async move { t1.await?; t2.await?; process(&structfrominnert1,&structfrominnert2);});
which I believe is the proper way to avoid blocking?

You can run two async blocks at the same time inside an async block using the join macro from futures-preview.

There's also a join function, which doesn't implicitly await the two futures.

Thanks @alice, it sounds good. However, I get a whole lot of cargo conflicts when I try to use

futures-preview = "^0.3.0-alpha.19"

and version 18 does not seem to have it.

If you are referring to the macro, it is available in 0.3.0-alpha.18. In fact it was introduced in 0.3.0-alpha.9, however as is also written in the documentation, you have to enable the feature async-await on the dependency, which can be done by adding

futures-preview = { version = "0.3.0-alpha.18", features = ["async-await"] }

to your Cargo.toml. Alternatively you can use the futures::future::join function, which does not require adding this feature, but requires you to manually call await, e.g.

// Inside an async block or function
let (result1, result2) = join(fut1, fut2).await;

The reason adding this feature is required, is that if you do not enable the feature, the crate will successfully compile on stable rust.

1 Like