Basics of Asynchronous JavaScript for Beginners

Javascript is a powerful lightweight, interpreted, object-oriented web based scripting language. JavaScript used to develop client side web pages more interactive.
JavaScript is a single threaded language which means you can run single operation at a time. Therefore when you run more tasks at the same time your browser may not respond until the given task is completed.
Synchronous JavaScript
Synchronous means running given task at same time. Assume an instance like below.
<body>
<button>Button</button>
<script>
const btn = document.querySelector('button');
btn.addEventListener('click', () => {
alert('Hello');
let msg = document.createElement('p');
msg.textContent = 'Text content.';
document.body.appendChild(msg);
});
</script>
</body>
Here while each operation is processing no other operation can occur. The text content is not displayed until you press Ok in the alert box. This is a simple demonstration of synchronous Javascript.
But there are instance where your function need to use a result of another function. For example you are loading an image and you need apply filter on that image. Here you need to wait for the image to load first before executing any other operations. This is the basis of asynchronous programming. Here through asynchronous code we can make, fetch image process running, and then wait until the result has returned before running filter process.
Asynchronous JavaScript
Asynchronous programming in JavaScript was introduced to solve such kind of problems. Asynchronous JavaScript can make you execution wait until a particular task needs to be completed. Asynchronous code is achieved in JavaScript in many ways.
- Traditional methods in JavaScript : (i) setTimeout() (ii) setInterval() (iii) requestAnimationFrame()
- Using Async callback / Promises
- Using async/await
Traditional JavaScript methods for asynchronous programming.
setTimeout() : setTimeout() method executes block of code after specified time. In the code below I have declared a function inside the setTimeout() function. Here mySetTimeOut() function executes after specified 2 s. Where as ‘Hello everyone. ‘, a console log statement and Hello on web page get printed initially. Then after 2 s alert box is displayed and then the myFunc() function is executed.
<body>
<p id="root"></p>
<script> let myFunc = function () {
console.log('myFunc : another function.')
}
let mySetTimeOut = setTimeout(function () {
alert('Hello, This is an alert.');
console.log('After 2 s')
myFunc(); }, 2000) console.log('Hello everyone.');
document.getElementById('root').innerHTML = 'Hello .';</script>
</body>
setInterval() : setInterval() method calls a function at specified intervals. (setInterval() method will continue calling the function until clearInterval() is called, or the window is called.)
<body>
<p id="demo"></p>
<script> function displayTime() {
let date = new Date();
let time = date.toLocaleTimeString();
document.getElementById('demo').textContent = time;
} setInterval(displayTime, 1000);
</script>
</body>
In the above code we have used setInterval() method. This calls the displayTime() function every 1 s. Therefore you can see a digital clock on you web page.
Asynchronous callback
Asynchronous JavaScript can be using callbacks too. Async callbacks are functions that are specified as arguments when calling a function which will start executing in the background. When background code finish execution, it calls the callback function to let that know that it has finished executing.
As they are they called back the name derived as callbacks. And the function containing callbacks are responsible for executing the callbacks.
Give below is an example for use of callbacks.
<script>
let callbackFunc = function (value) {
console.log(value);
}
let getValue = function (callback) {
let value;
console.log('Hello')
setTimeout(function () {
value = 10;
callback(value);
return value;
}, 1000);
};
getValue(callbackFunc);</script>
Here 'Hello' message is printed on console and after 1 s the callback function is called and value 10 will be printed on the console.
Important : Not all callback are async.
Promises
Promises are new features in JavaScript that let you assign further actions until after a pervious action has completed. So it is useful to set up sequence of async operation to work.
Promise is as the meaning is a kind of promise that will be made to return in future. There is no guarantee when the operation will complete and result will be returned, but there is a guarantee if the promise fails the code provided will handle the case with a catch statement.
Important : Promises uses catch() block if any of the .then() block fails. Like try catch blocks in synchronous code. However try catch does not work with promises. But it works with async/await.
Most modern web API use promises for functions that perform lengthy tasks. Here we are looking only the custom promises.
Building custom promises.
Promises can be built on our own using Promise() constructor. This is mainly used mainly when you got code based on old asynchronous API that is not promise based, which you need to make as promise. Here in code below is a simple use of custom promises.
<body>
<script>
let myFunc = function () {
let age;
return new Promise(function (resolve) {
setTimeout(function () {
console.log("I will handle the problem");
age = 10;
resolve(age);
}, 1000);
});
};
myFunc().then(function (age) {
console.log(age);
});
console.log("My age ");
</script>
</body>
Custom promises can also be chained to perform sequence of task.
<body>
<script>
let myFunc = function () {
let sum;
return new Promise(function (resolve) {
setTimeout(function () {
sum = 10;
resolve(sum);
}, 1000);
});
};
myFunc().then(function (sum) {
console.log(sum);
return sum + 100;
}).then(function (sum) {
console.log(sum);
return sum + 200
}).then(function (sum) {
console.log(sum);
});
console.log("Initial message")
</script>
</body>
Note : Queue event - Asynchronous operations like promises are put into event queue, which runs after the main thread has finished executing.
Making asynchronous programming with async/await
These are recent addition to JavaScript and part ECMAScript 2017. These makes asynchronous code easier to write and read. They make async code to look like old synchronous code.
We make an async function by putting async keyword in-front of function declaration. The await keyword is used pause a code until a promise full fills.
Given below simple implementation of async keyword along with await keyword.
<body>
<script>
function myFunc() {
let sum = 10;
console.log("Before the setTimeout");
return new Promise(function (resolve, reject) {
setTimeout(function () { //This only for stimulation no need of setTimeout inside promise
sum = 10;
resolve(sum);
}, 2000);
})
}
async function print() {
let sum = await myFunc();
console.log(sum);
console.log("This is after printing sum");
}
print();
</script>
</body>
Here “Before the setTimeout” statement is printed initially on the console. Then value of sum is printed after 2 s following another statement.
Here we have made print() function async by using async keyword and we have used await keyword before calling myFunc() function. Therefore this makes the print function to pause until the promise is fulfilled.
Conclusion
There are pros and cons in each method of implementing asynchronous code. Therefore based on different requirements different approaches can be made in asynchronous JavaScript programming.