Can anyone explain async programming with Futures

I read the docs but I don't understand why futures and how it works..

It will be better if u will First create synchronous code then turn that into asynchronous code with futures

I find that this article can be good at giving an initial understanding of how it works. Also, which docs did you read? Did you read the Tokio tutorial?


Can u pls provide example with a

synchronous code and turn that into async code with async keyword

No async keyword? Using async/await is an important part of async programming.

Assuming you just want more insight into how the Future trait works and might be implemented manually, I have constructed a playground which shows an example of using Futures without the async/await sugar:

This example runs some "timers" concurrently on a single thread.

This example has a number of "gotchas" due to it's simplicity:

  • The playground doesn't show live output, so you'll need to copy it locally to view the timers running properly.
  • There's a lot of syntax noise due to features that aren't relevant in this example, but would be in a bigger program (Wake, Context, Pin, etc).
  • The "executor" is just a loop. Most executors (e.g. tokio) are much smarter about when they poll futures.

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.