Explain to me asynchronous JavaScript (callbacks, promises, async/await) like I'm 5 years old, thread 👇

#javascript #100DaysOfCode
JavaScript code is executed synchronously, i.e. line by line in the order it's written, and one line at a time.
Now let's say we had to make a network request to get the description from a server and our user has a bad Internet connection so it takes some time to resolve.
Our code works, but during the time we were getting the description from the server, our page was frozen, which is quite frustrating for the user... 😠

One approach to fix that is called "callbacks".
We pass getDescription a function to handle the result (i.e. description).

The request is made, the page works just fine and it's not frozen. We then get a response from the server with 2 parameters: an error (which is empty if the call was successful) and the description.
Guess what? We just learned one approach of handling asynchronous code in JavaScript.

It's asynchronous because our browser did 2 things at a time without getting stuck.
Another approach to asynchronous code is called "Promise"s.

getDescriptionFromServer returns a Promise object. The Promise object has a function "then" to handle success and a function "catch" to handle errors.
If you find this second approach confusing, there's a beautiful syntax to do the same thing and it's our favorite one.
If you want to use "await" in a function, this function has to be declared with the keyword "async".
That's it 🎉.

If you're still struggling with understanding asynchronous JavaScript, it's totally fine and is not your fault.

We suggest you take your time to read this thread a few more times or find another resource that explains it way better than us.
If you managed to understand though, congrats!

Now go ahead and build amazing UIs that can do expensive work asynchronously without being a pain to their users.
Props to the amazing and talented @soylaila_ for this beautiful illustration she made for us 😍.
You can follow @tinloof.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: