Asynchronous in JavaScript

JavaScript is single threaded programming language so it is blocking synchronous in nature but environments use different APIs and other stuff to make the language asynchronous and make it perform different asynchronous tasks like set Interval, set Timeout, Promises, and Async/await.

You might want to learn about JavaScript Basic before hopping into Asynchronous in Javascript.

Asynchronous in Javascript can be achieved in the following ways:

Call Back Function

 The callback function is a function that takes functions as arguments.

Example:

function sumOfTwoNumbers(a,b){
return a+b;

}

function multiple(a, b){
return a*b;

}

console.log(sumOfTwoNumbers(2,3), 10);

This returns 50 as the sum returns 5 and multiples 10.

The callback is used when the result of the previous function is required to perform the next function.

This concept of the callback function is also used in currying of function.

Currying is simply a method in which multiple functions are returned inside another function:

function a(x) {

return function b(y) {

return function c(z) {

return x * y * z;

};

};

}

console.log(a(1)(2)(3));

This helps in checking the results of previous functions and doing tasks accordingly.

JavaScript achieves Asynchronous systems using web APIs like setTimeout and setInterval.

function sum(a, b) {

return a + b;

}

function multiple(a, b) {

return a * b;

}

setTimeout(() => {

console.log(sum(2, 4));

}, 1000);

console.log(multiple(sum(2, 3), 10));

Here, 6 is printed after 50 even if it is invoked before as it is executed asynchronously using the setTImeout and is printed after 1000 ms.

setInterval(()=>{

console.log(sum(2, 4));

},1000);

Here, 6 is printed every 1000 ms and occurs indefinitely unless clearInterval is called as

function sum(a, b) {

return a + b;

}

const setI = setInterval(() => {

console.log(sum(2, 4));

}, 1000);

function x() {

clearInterval(setI);

}

setTimeout(() => {

x();

}, 5000); This makes the function run for 4 times before clearing the Interval.

Asynchronous is mainly used to perform extensive tasks. Several tasks that can utilize the asynchronous nature are password hashing, data retrieving from databases, and another intensive task that may freeze the system if asynchronous is not used.

Promises:

Promises in JavaScript is a special object which encapsulates the asynchronous result of the asynchronous function. Let’s create a Promise which has resolved or rejected state and does a different task on basis of that.

Let’s create a new Promise :

const prom = new Promise((resolve, reject)=>{
function multiple(a, b){

return a*b;

}

if(multiple(2,5)>6){
resolve(“Resolved”)

}

else{

reject(new Error(“Rejected”))

}})

prom.then((result)=> console.log(result)).catch((err)=>console.log(err));

This returns Resolved as multiple(2,5) is greater than 6 and all this occurs asynchronously.

Promise Chaining:

This is done if the value return through and .then returns another promise which needs to be resolved. It is mainly used in fetch API.Example:

const URL = “https://pokeapi.co/api/v2/pokemon/1”;

fetch(URL)

.then((res) => res.json())

.then((res) => console.log(res))

.catch((err) => console.log(err)); This returns the result as:

Asynchronous in Javascript: Promise chaining

This is achieved using Promise chaining.

Promise. all:

This method is used to perform multiple promises and fetch data if all of the promises is either resolved or rejected.

Example:

const url = “https://pokeapi.co/api/v2/pokemon/1”;

const url2 = “https://pokeapi.co/api/v2/pokemon/2”;

Promise.all([fetch(url), fetch(url2)])

.then((res) => Promise.all(res.map((item) => item.json())))

.then((res) => console.log(res.map((res) => res)))

.catch((err) => console.log(err));

This method fetches two data and returns data if both fetches occur.

Async/ await:

This helps to write Promises easily. The Async keyword makes the function asynchronous and awaits the keyword waits for the result of the asynchronous function. await can only be used inside the async function.

The async function returns a Promise which can be used .then syntax or by using a try-catch block. This helps in error catching. Async function has pending and either resolved or rejected state and performs the task according to its state.

Example:

async function ABC(a, b) {

return a + b;

}

const x = async () => {

try {

return console.log(await ABC(2, 3));

} catch (error) {

console.log(error);

}

};

x();

This returns 5 and the task is performed asynchronously.

Await keywords can be used to wait for promises to either resolve or be rejected.

const URL = “https://pokeapi.co/api/v2/pokemon/1”;

const b = async () => {

  try {

    const response = await fetch(URL);

    const data = await response.json();

    console.log(data);

  } catch (err) {

    console.log(err);

  }

};

b();

This is easier to read than promise chaining and is a newer method to achieve the task.

Try catch block can be used to await for multiple promises to resolve.

const promisea;

const promiseb;

const promisec;

async function result() {

try{

    const result1 = await promisea;

    const result2 = await promiseb;

    const result3 = await promisec;

    console.log(result3);

    console.log(result2);

    console.log(result3);

}catch(err){
console.log(err);

}

}

result(); This returns if all promises are fulfilled and throw an error if any promise is rejected.

For more similar content, Visit Enlight Info.

One thought on “Asynchronous in JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *