Asynchronous JavaScript

JavaScript is single-threaded, meaning it executes one operation at a time. However, asynchronous programming allows JavaScript to handle time-consuming tasks (e.g., fetching data, reading files) without blocking the main execution thread.

Callbacks

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

Example of a Callback Function

function fetchData(callback) {
  setTimeout(() => {
    console.log("Data fetched");
    callback();
  }, 2000);
}
  
function processData() {
  console.log("Processing data...");
}
  
fetchData(processData);

fetchData simulates an asynchronous operation using setTimeout.

processData is executed after fetchData completes.

Promises

A promise represents a future value and has three states:

  1. Pending – Initial state, operation in progress.

  2. Fulfilled – Operation completed successfully.

  3. Rejected – Operation failed.

Creating a Promise

let fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    let success = true; // Change to false to test rejection
    if (success) {
      resolve("Data received");
        } else {
      reject("Error fetching data");
    }
  }, 2000);
});
  
fetchData
  .then(result => console.log(result)) // Executes if resolved
  .catch(error => console.log(error)) // Executes if rejected
.finally(() => console.log("Operation complete"));

.then() runs when the promise is resolved.

.catch() runs when the promise is rejected.

.finally() runs regardless of success or failure.

Conclusion

Asynchronous programming allows JavaScript to handle time-consuming operations efficiently. Callbacks, promises, and async/await help manage asynchronous workflows. The next section will explore DOM manipulation, which enables JavaScript to interact with web pages dynamically.

Packly

Professional 3D packaging renders for modern brands. Transform your product presentation today.

Company

Legal

Privacy

Terms of Use

© 2025 Packely. All rights reserved.