Asynchronous Programming in javascript
Asynchronous progamming is a feature in which you don’t have to wait for a function execution to complete before going to your next command.
How can you run tasks in asynchronously in JavaScript?
The modern ways to run tasks asynchonously are :
Promises
CallBack
Async/Await
Using Promise for asynchronous programming
A promise is a function that takes another function (called executor function) as a parameter.
The executor function is the one that runs asynchronously.
This executor function takes two parameters (the parameters are also functions themselves):
- Function to be called when the Executor function completes succesfully (let's call it resolvedFunction)
- Function to be called when the Executor function encounters an error (let's call it rejectedFunction)
The executor function then calls one of these functions based on success/failure. If the executor function completes succesfully, it calls resolvedFunction() with the result you want to return from the asynchronous operation. If the executor function encounters error, you would typically call rejectedFunction with the error message.
The resolvedFunction and rejectedFunction are called only after the executor completes (in other words: after
the promise is settled)
Below is an example of how it works:
1 | var myPromise = new Promise((resolvedFunction,rejectedFunction)=>{ |
Using CallBack for asynchronous programming
This video that I made explains how to use CallBack with an example.
1 | function getFile(); |
Sometimes functions like getFile() trigger getting file from a server and don’t wait for the file to be received. In such a case, useFile() would start executing before it gets the file and cause an error. We can solve this using CallBack. We can pass the useFile function inside getFile(). Then we can ensure that we call useFile only after the process of getting file is complete. It looks like this:
1 | function getFile(callBack){ |
async/await
Promise chains can be difficult to read. Look at this example. The .then() chains make it difficult to read:
1 | async function returnsPromise1(parameter1){ |
We see that this chaining can get difficult to read. Using async/await makes it more readable, as you see below.
1 | async function returnsPromise1(parameter1){ |