wap-notes

Synchronous and Asynchronous Programming in JavaScript

Synchronous Programming

Asynchronous Programming


Promises

What is a Promise?

Creating a Promise

let promise = new Promise((resolve, reject) => {
  let success = true; // Simulating a condition
  if (success) {
    resolve('Task completed successfully!');
  } else {
    reject('Task failed.');
  }
});

.then() and .catch()

Using .then()

Using .catch()


Fetch Method

Definition: The fetch() method is used to make network requests and returns a promise that resolves to the response object. This can be used to make API calls to retrieve or send data.

Syntax:

fetch(url)
  .then(response => response.json()) // Converting the response to JSON
  .then(data => console.log(data)) // Handling the data
  .catch(error => console.error('Error:', error)); // Handling errors

Async/Await

Definition: async/await provides a way to work with asynchronous code in a more synchronous-looking manner, making the code easier to read and understand.

Example:

async function fetchData() {
  try {
    let response = await fetch('https://api.example.com/data');
    let data = await response.json();
    console.log(data);
  } catch (error) {
    console.log('Error:', error);
  }
}

fetchData();

Explanation:

When to Use Async/Await