Home  >  Article  >  Web Front-end  >  Asynchronous programming Callbacks, Promises & Async Await

Asynchronous programming Callbacks, Promises & Async Await

WBOY
WBOYOriginal
2024-09-11 06:43:021072browse

Asynchronous programming Callbacks, Promises & Async Await

Asynchronous programming in JavaScript allows you to perform tasks like making API calls, reading files, or querying databases without blocking the execution of other code. This is crucial in JavaScript, particularly in web development, where responsiveness and performance are key.

Key Concepts

1. Callbacks:

A function passed as an argument to another function, which is executed after the completion of an asynchronous operation.

Example:

function fetchData(callback) {
setTimeout(() => {
callback("Data fetched");
}, 1000);
}

fetchData((data) => {
console.log(data);
});

2. Promises:

An object representing the eventual completion or failure of an asynchronous operation.

A promise can be in one of three states: pending, fulfilled, or rejected.

Example:

let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});

promise
.then((data) => console.log(data))
.catch((error) => console.log(error));

3. async and await:

async functions automatically return a promise and are used to simplify the handling of promises.

await pauses the execution of an async function until the promise is resolved, making the code easier to read and write.

Example:

async function fetchData() {
try {
let data = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched");
}, 1000);
});
console.log(data);
} catch (error) {
console.log(error);
}
}

fetchData();

Asynchronous Patterns

Callback Hell: A situation where callbacks are nested within other callbacks, making the code difficult to read and maintain.

Promise Chaining: A pattern to avoid callback hell by returning promises and chaining .then() and .catch() methods.

Async/Await: A more modern and cleaner approach to writing asynchronous code, which avoids promise chaining and makes the code more synchronous-looking.

Use Cases

API Calls: Fetching data from a server.

Timers: Using setTimeout or setInterval.

File Operations: Reading or writing files in a non-blocking manner.

Event Handling: Handling events like clicks, keypresses, etc.

Asynchronous programming in JavaScript is essential for building responsive, efficient applications, particularly when dealing with I/O-bound operations.

The above is the detailed content of Asynchronous programming Callbacks, Promises & Async Await. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn