Learn Async And Await In A Funny Way

Table of contents

No heading

No headings in the article.

I'll be happy to explain async and await to you in a way that you can understand. Are you ready to learn? Great!

Imagine you have two friends, Bob and Alice, and they both want to talk to you at the same time. Normally, you can only listen to one person at a time, right? But what if I tell you that you can listen to both of them at the same time and respond to them whenever they finish speaking? That's what async and await do!

So, let's say Bob starts talking to you first, and he asks you a question. Instead of waiting for him to finish talking before you respond, you can tell Bob, "Bob, I'm going to listen to Alice too, but don't worry, I'll come back to you when you're done." This is called "awaiting" Bob's response.

Then, you turn to Alice and say, "Alice, I'm going to listen to Bob for a bit, but I'll come back to you when he's done." This is also an "await" statement.

Now, while Bob is talking, you can keep an ear out for Alice. If Alice says something interesting, you can respond to her right away, even if Bob is still talking. This is the power of "async" (short for asynchronous)!

Once Bob finishes talking, you go back to him and respond to his question. After that, you go back to Alice and continue your conversation with her. This way, you can have multiple conversations happening at the same time without having to wait for each person to finish before moving on to the next.

In programming, async and await work in a similar way. When you have a task that takes some time to complete, like loading a picture or fetching data from the internet, you can use async and await to keep your program responsive.

By using the "async" keyword, you tell your program, "Hey, this task might take some time, but don't wait for it to finish. Keep doing other things and let me know when it's done."

Then, when you want to wait for the task to finish and get the result, you use the "await" keyword. It's like saying, "Okay, let's pause here and wait for the result of this task. Once it's ready, we can continue."

So, async and await allow your program to do multiple things simultaneously and handle long-running tasks without blocking the whole program. Just like how you can listen to both Bob and Alice at the same time and respond when they finish speaking.