Javascript — Asynchronous programming

Toddypet
4 min readAug 14, 2021

--

In this article, I will explain how to use Javascript for Asynchronous programming.

Before we start, let’s first think about why we need Asynchronous programming. Asynchronous programming exists to solve the problem of blocking and save your time for waiting for the previous step to complete.

In the below example, considering each task takes 10 sec to complete. Synchronous will take around 30 sec to complete three tasks. On the other hand, asynchronous will only take a little more than 10 sec

Callback v.s. Promise v.s. Asyn/await

When you google javascript asynchronous, it might come up with the above glossaries. In short, they are all tools you can use to make your code asynchronous. The time when it comes out: callback -> Promise (ES5) -> Async/await (ES6). Instead of considering as different tools, you should consider that each of them is an improvement of the previous one. We develop a new one for the purpose of making your code easier to read.

Callback

callback function = pass on the function as a parameter to control the sequence. Once you pass on a callback function, it will be put into event loop, in this way, main thread can carry on to run the next step and we only handle the function in event loop when there is some free time in main thread. In this way, we can control the sequence of code execution and also make javascript asynchronous.

For more detail on how event loop works, please check my article: https://toddypet.medium.com/javascript-event-loop-2c8623b02568

To put it in code. In below example, I use call back function to present how to manage to print task in sequence: Task 1 -> Taks 2 -> Taks3

SetTimeout is the most common callback feature we see in code. it accepts a callback function and a time. In below example, you can see how Iuse setTimeout to delay the taskDone to print at the end of all of the execution

However, if you chain up with multiple callbacks to control the sequence as they have dependencies on the previous step. we call it callback hell

Promise

Promise have been introduced to solve the issue we have below while using callback

  1. hard to read the code when the function can be anywhere in your index.js file
  2. callback hell

Promise is a constructor, to create your promise there are some steps you need to follow

1.create a promise instance and set up resolve reject

2.use .then/.catch handler to handle the flow

.then(): will listen to what has been returned in resolve

.catch(): will listen to what has been returned in reject

You can also chain multiple promises in handler. Taking the previous example we have, to print Task 1 -> Task 2, can be chained as below, simply put your taskTwo function as a return. In this way, you can make your code easier to read. Instead of jumping to different lines, you can read it from top to bottom as the chain behavior clear up the function flow

Async/Await

However, the chaining is still not intuitive enough. To make the code more readable and make it similar to how we write synchronous code. Asyn/Await have been introduced to make your code easier to read and better way of error handling

  1. create a promise instance
  2. add async tag in front of the function. (NOTE: async function will return a promise)
  3. In async function, mark await as a waiting point

To handle the error, we combine it with try….catch…

Once it rejects with error, it will stop the flow and execute the catch block

Conclusion

as you can see above, these technologies have been developed to do asynchronous programming. Also, JS keep making improvement (from callback -> async/await) to make your code easy to read. In this article, I aim to explain the relationship between different tools. There are more APIs you can use on the top of these tools:)

Ref

https://javascript.info/async

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

--

--

Toddypet

Hello, I am Heidi. I started this medium blog to post all of the note I have when I am learning new things. Hope you find it useful as well:)