Learn in and out about Asynchronous Javascript Software Development


 

We all agree that handling asynchronous javascript code is a confusing task, the good news is that although this is a difficult thing to learn and manage javascript standard and technologies contains built-in environments for asynchronous events.

This article will explain everything you need to know about asynchronous javascript including callback function, setTimeout method, setInterval method, javascript promises method, and javascript async/await


Javascript callback

Javascript callback is a technique to call a function inside another function. This technique passes the callback function as an argument to another function. The popular use of this callback technique is when we want a callback function to run after another function has finished running.

The syntax for javascript callbacks is as follows:

function AnotherFunction (argument1, argument2 …., CallbackFunction) {

CallbackFunction(someValue);

}

Syntax explained:

In the above syntax, a function CallbackFunction is passed as an argument to a function AnotherFunction.

 

Example 1: Javascript Callback function example

Think of a real-life example, suppose we have a web page application containing an HTML form with two input elements and a submit button. We need a user to perform the following: submit two numbers, click a button to calculate the sum of two numbers, and display the result on a web page.

With this example, we have the following two functionalities: a function to add two numbers, and a function to display the sum of two numbers. You can see that the function to display the sum of two numbers needs to wait until the function to add two numbers has finished running. Also, the function to display the sum of two numbers can be called inside the function to add two numbers so that the result will be displayed after the addition of two numbers is complete.

Therefore we will create two functions: calculateSum(), and displaySum()

calculateSum() function will calculate the sum of two numbers and pass three arguments: a, b, and callbackFunction

function calculateSum(a,b, callbackFunction){

let sum = a+b;

callbackFunction(sum);

}

displaySum(value) function will display the sum of two numbers in an <p> HTML element with an id = “result”.

Here are HTML codes and javascript codes to implement the applications in example 1 above:

<!DOCTYPE html>

<html>

<head>

<title>My Javascript Callback Example</title>

</head>

<body>

<h2>Javascript Callback Example</h2>

<input id="num1" type="number" placeholder="Enter First Number"><br>

<input id="num2" type="number" placeholder="Enter Second Number"><br>

<button onclick="calculateSum(num1,num2,displaySum)">Compute</button>

<p id="result"></p>

<script>

const num1 = parseInt(document.querySelector('#num1').value);

const num2 = parseInt(document.querySelector('#num2').value);


function calculateSum(a,b, callbackFunction){

let sum = a+b;

callbackFunction(sum);

}

function displaySum(value){

document.querySelector('#result').innerHTML = value;

}

</script>

</body>

</html>

 

The output is here:

 


 

 

Callback functions are initially used in asynchronous functions when one function needs to wait for another function to finish running.

 

What is Asynchronous JavaScript?

There are situations where other functions need to run in parallel with other functions, this is common in cases where resource-intensive functions need to run only when needed or need to wait for other parallel functions to finish.

Typical examples of asynchronous functions includes: setTimeout(), and setInterval()

We shall understand the above two functions by using real-life examples here:


setTimeout() Method:

This method calls a function once after a specified time delay. The syntax for setTimeout() method is here:

let delayItem = setTimeout(function, [timerDelay], [parameter1], [parameter2] ...);

Syntax explained:

The method takes in three items: the function to be executed after a specified time delay; a time delay in milliseconds, and function arguments.

The clearTimeout() method is used to stop the execution of the setTimeout() method.

 

Example 2: Settimeout Example

Let’s think of an example in which a user enters first name and last name. Then the system will store values for first name and last name and then display the full name. In this example, the full name will be displayed after 4000 milliseconds. The javascript code to perform this task is as follows:

<!DOCTYPE html>

<html>

<head>

<title>Settimeout Example</title>

</head>

<body>

<h1>Settimeout Example</h1>

<h2>Registration Form</h2>

<input type="text" id="firstname" placeholder="Enter Fistname">

<input type="text" id="lastname" placeholder="Enter Lastname">

<button onclick="registerUser()">Register</button>

<p id="fullname" style="font-size: 16px; font-weight: bold; color: green;"></p>

<script>

const firstname = document.querySelector('#firstname').value;

const lastname = document.querySelector('#lastname').value;

function Fullname(fname,lname,displayFull){

let fullname = fname+" "+lname;

displayFull(fullname);

}

function displayFullname(value){

document.querySelector('#fullname').innerHTML=value;

}

function registerUser() {

setTimeout(() => {

Fullname(firstname,lastname,displayFullname);

}, 4000)

};

</script>

</body>

</html>

 

The output is here:

 


 

 

setInterval() Method:

This method repeats the execution of a function after specified time intervals. The syntax is as follows:

let intervalItem = setinterval(function, [timerInterval], [parameter1], [parameter2] …);

 

Syntax explained:

The method takes in three items: the function to be repeatedly executed after a specified time interval; a timer interval in milliseconds, and function arguments.

Also, the clearInterval() method is used to clear execution of the setInterval() method.

 

Example 3: Javascript Set interval Example

In this example, we are going to automate a betting game of chance, in which at an interval of 1000 milliseconds a random number between 0 and 1 is generated. The counter will be updated at each generated random number, then the random numbers are saved in the array variable. The game will stop after the counter reaches 10 counts and the score is recorded when the attained random number is greater or equal to 0.5. The result of the attempt will be WON if the score is greater or equal to 5 otherwise a LOSE result will be displayed.

Here are the HTML and javascript codes to implement the game:

<!DOCTYPE html>

<html>

<head>

<title>Set Interval Example</title>

</head>

<body>

<button onclick="playGame()" id="game-start" style="background-color: green; font-size: 16px; font-weight: bold; color: white; padding: 10px; margin: 5px; border-radius: 10px; cursor: pointer;">Start Game</button>

<button onclick="stopGame()" id="game-stop" style="background-color: red; font-size: 16px; font-weight: bold; color: white; padding: 10px; margin: 5px; border-radius: 10px; cursor: pointer;">Stop Game</button>

</body>

<p id="currentnumber"></p>

<p id="attainednumbers"></p>

<p id="counter"></p>

<p id="score"></p>

<p id="result"></p>

 

<script>

const arr = [];

let counter = 0;

let score = 0;

let gameId;

function playGame() {

if (!gameId) {

gameId = setInterval(startGame, 1000);

}

}

function stopGame() {

clearInterval(gameId);

gameId = null;

}

function startGame(){

let randnum = Math.random();

document.querySelector('#currentnumber').innerHTML = "Current Number: " + randnum;

arr.push(randnum);

console.log(arr);

document.querySelector('#attainednumbers').innerHTML = "Attained Numbers: " + arr;

counter=counter+1;

document.querySelector('#counter').innerHTML = "Counter: " + counter;

if(counter>10){

stopGame();

}

if(randnum>=0.5){

score=score+1;

document.querySelector('#score').innerHTML = "Attained Score: " + score;

if(score>=5){

document.querySelector('#result').innerHTML = "YOU WON!";

}else{

document.querySelector('#result').innerHTML = "YOU LOSE!";

}

}

}

</script>

</html>

 

How to run the game?:

Copy the codes above and open any text editor of your interest then paste and save the file as “game.html”. Right-click the file choose to open with the browser and test to play the game by clicking the “Start Game” button.

 

The output is here:

 


 

 


 

 


 

 

Javascript Promises object

Javascript promise object handles both codes that need to take some time called Producing code and codes that must wait for the result known as Consuming code.

The syntax for javascript Promise is here:

let myAction = new Promise(function(myAction, myActionReject) {

myAction();

myActionReject();

});

myAction.then(

function(value) { /* actions performed if successful */ },

function(error) { /* actions performed if some error */ }

);

Syntax explained:

The syntax takes in two callback functions: myAction, myActionReject

When successful myAction() will be executed otherwise if there are errors the myActionReject() is executed. Also with myAction.then will wait until a promise is fulfilled to execute codes for a successful promise and display errors if some errors occur.

 

Example 4: Javascript Promises Example

Think of a login example where we first test for login credentials, if successful a user is redirected to the dashboard page else the login attempt is rejected and the user is redirected to the login page.

The codes to implement this scenario are here:

<!DOCTYPE html>

<html>

<head>

<title>Login Form</title>

<style>

div{

align-content: center;

}

button{

background-color: lightgreen;

margin: 10px;

font-size: 16px;

font-weight: bold;

padding: 10px;

border-radius: 10px;

}

#username{

margin: 10px;

font-size: 16px;

font-weight: bold;

padding: 10px;

border-radius: 10px;

}

#password{

margin: 10px;

font-size: 16px;

font-weight: bold;

padding: 10px;

border-radius: 10px;

}

</style>

</head>

<body>

<div id="wrap">

<h1>Login Form</h1>

<input type="text" id="username" placeholder="Enter username">

<input type="password" id="password" placeholder="Enter password">

<button onclick="Login()">Login</button>

</div>

<script>

function Login(){

let myAction = new Promise(function(myActionResolve, myActionReject) {

const username = document.querySelector("#username").value;

const password = document.querySelector('#password').value;

if(username=="johndoe" && password=="123456"){

myActionResolve();

}else{

myActionReject();

}

});

myAction.then(

function() { document.querySelector('#wrap').innerHTML = "<h1 style='background-color: lightgray; color: green;'>Wellcome!</h1>"; },

).catch(

function() { document.querySelector('#wrap').innerHTML = "<p style='background-color: lightgray; color: red; font-weight: bold;'>Incorrect Username or Password</h1><h1>Login Form</h1><input type='text' id='username' placeholder='Enter username'><input type='password' id='password' placeholder='Enter password'><button onclick='Login()'>Login</button>"; }

);

}

</script>

</body>

</html>

 

The output is here:

 


 


 

Javascript async and await

Promises are written easily using javascript async and await keywords in which async executes a function to return a promise and with await keyword the function execution waits for a promise.

The syntax is as follows:

async function promiseFunc() {

 

}

promiseFunc().then(

function() { codes executed if successful } ).catch(

function() { codes executed if there are errors }

);

Syntax explained:

The syntax starts with async keyword to enable the function to return a promise. To consume a promise the promiseFunc().then is used to execute codes if successful otherwise .catch() is used to execute codes if there are errors.

With await keyword execution is delayed to wait for a promise to be resolved. The syntax is here:

let promiseValue = await promiseFunc;

 

Conclusion

Congratulations on reading this article from start to end, this is another great opportunity for you to have improved knowledge of JavaScript and how to work with asynchronous Javascript.

The examples cited in this article help you visualize real-life scenarios about javascript promises and async/await. Our team of experts would appreciate getting comments from you on issues with confusion and/or complexities and would be happy to come back and respond on these issues. You can send an email to admin@softcodetactics.com or use the contact form and comments pages on this blog.

Our team of experts plans to add more content and examples here, please return frequently to this site for recent updates on topics about Javascript.


Post a Comment

0 Comments