Stream: general

Topic: Await multiple futures

Martin Asquino (Mar 27 2020 at 01:17, on Zulip):

Hello! Not sure if this is the place to ask this, but I'm trying to build a vec of futures and await/join them in a non-async function. Something like this:

fn some_function() {
                    use futures::executor::block_on;
                    use futures::future::join_all;
                    use futures::task::SpawnExt;

                    let futs: Vec<_> = some_vec
                        .map(|cl| tokio::task::spawn_blocking(async || { cl }))

                    let result: Vec<i32> = block_on(join_all(futs));

My issue here is that clearly I'm misunderstanding what block_on or join_all do, because I don't get a Vec<i32> from that last line, but a Vec<Result<impl core::future::future::Future, tokio::task::error::JoinError>> instead.

My intention is to basically spawn that vec of futures and await them in parallel, to then join them to the main thread.

Can someone help me understand what I'm doing wrong here?

Laurențiu Nicola (Mar 27 2020 at 07:37, on Zulip):

I think you wanted to say block_on(join_all(futs)) instead of block_on(join_all(c))? But it does seem written in a round-about way, e.g. I don't think you need spawn_blocking since your future doesn't block so spawn might be enough. There's also FuturesUnordered which may be more efficient than join_all.

Laurențiu Nicola (Mar 27 2020 at 07:39, on Zulip):

Assuming that c is a typo, I'm still not sure why you're getting the error, since block_on(join_all(futs)) should return a Vec<Option<CodeLens>> if some_async_function returns an Option<CodeLens>.

Martin Asquino (Mar 27 2020 at 09:04, on Zulip):

Ah yeah that was a typo, my bad. some_async_function there returns a failure::Fallible<CodeLens>.

Laurențiu Nicola (Mar 27 2020 at 09:14, on Zulip):

So you're getting that error on the block_on line?

Laurențiu Nicola (Mar 27 2020 at 09:16, on Zulip):

Try checking the types, or comment out bits of code to see where is the type mismatch. From that error I get that block_on(join_all(c)).into_iter().map(|c| c.unwrap()) yields Futures

Martin Asquino (Mar 27 2020 at 09:17, on Zulip):

ok I managed to get it working, had to change that to a spawn and was missing a second unwrap on that map in the end. I didn't know spawn returned a result though :thinking:

Martin Asquino (Mar 27 2020 at 09:27, on Zulip):

also, thank you! :grinning:

Last update: May 29 2020 at 17:20UTC