Asynchronous Programming in JavaScript

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Akshat Garg

What is
Asynchronous
Programming

in
Akshat Garg

Asynchronous Programming

Asynchronous Programming is a
programming paradigm that allows code
to be executed in a non-blocking manner.

In JavaScript, asynchronous
programming is commonly achieved
using callbacks, promises, and
async/await functions.
Akshat Garg

Callbacks

Callbacks are functions that are passed as


arguments to other functions and are
executed once the operation they are
associated with completes.

Callbacks are used to handle asynchronous


operations such as network requests, file
I/O, and other time-consuming tasks.

A callback function is passed to an


asynchronous function and is executed
when the operation completes.
Akshat Garg

Example :

function fetchData(url, callback) {


fetch(url)
.then(response => response.json())
.then(data => callback(data))
.catch(error => console.log(error));
}

fetchData('https://api.example.com/
data', data => {
console.log(data);
});
Akshat Garg

Promises

Promises are objects that represent a value


that may not be available yet but will be
resolved at some point in the future.

Promises are used to handle asynchronous


operations in a more readable and
structured manner.

A promise can be in one of three states:


pending, resolved, or rejected.
Akshat Garg

Example :
function fetchData(url) {
return fetch(url)
.then(response => response.json());
}

fetchData('https://api.example.com/
data')
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
Akshat Garg

Async/await

Async/await is a syntax for handling promises


in a more synchronous-looking manner.

Async/await functions are defined with the


async keyword and return a promise.

The await keyword can be used inside an


async function to wait for a promise to
resolve before continuing execution.
Akshat Garg

Example :
async function fetchData(url) {
const response = await fetch(url);
const data = await response.json();
return data;
}

fetchData('https://api.example.com/
data')
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});
Akshat Garg
Follow for More

You might also like