Is there a way to await inside a From or TryFrom?

I have some methods that needs to be awaited and gotta do it in TryFrom. I have searched the internet but there's no question or blog post. I have also looked at the APIs of some runtimes, mainly tokio and async-std (I use tokio). They do not seem to implement it as well.

Then I have started to think there is maybe a reason, maybe it is an antipattern in Rust.

I also do not want to use futures::executor::block_on because it throws "cannot spawn another async runtime inside async runtime", which makes it unpredictable to use.

So, the questions are:

  1. Is an async TryFrom or From antipattern? Can you explain or lead me to another thread about it?
  2. If not, how can I await inside TryFrom cleanly?

Thanks in advance.


Environment

  • Rust 1.57.0

There is no way. Use an ordinary method instead.

4 Likes

It's hard to say if it's pattern or antipattern if you can't do that at all.

No thread, just reference: Currently, async fn cannot be used in traits. The reasons for this are somewhat complex, but there are plans to remove this restriction in the future.

Basically it's something to discuss at some later date when what you want would actually be implementable.

Please note that even if async fn were supported in traits, the TryFrom trait would not be using that feature, so even then, it would still not be possible.

2 Likes

I'd argue it's a strong antipattern. If awaiting is needed, chances are this is an expensive, non trivial, transformation. From and TryFrom are for "simple and safe type conversions".

5 Likes

Yes, even if you're in non-async code, you shouldn't be performing a web request in a TryFrom impl.

5 Likes

Been there, asked that :sweat_smile:. Short story: it's an anti-pattern. You can try to do it if you are still curious, though (sometimes it's the only way to learn the lesson).

I was fixing my computer for last couple of days. Thanks, folks. Now, I understand.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.