How do you handle asynchronous operations in JS?

·

2 min read

Asynchronous operations (eg. fetching data from an API)

In JavaScript, you can handle asynchronous operations, such as fetching data from an API, using promises or async/ await syntax. Heres how you can do it:

Using Promises:

function fetchData() { return new Promise((resolve, reject) => { // Simulating an asynchronous operation, like fetching data from an API setTimeout(() => { const data = { message: 'Hello, World!' }; resolve(data); }, 2000); // Simulating a delay of 2 seconds }); }

fetchData() .then(data => { console.log(data); }) .catch(error => { console.error('Error:', error); });

Using async/await:

async function fetchData() { return new Promise((resolve, reject) => { setTimeout(() => { const data = { message: 'Hello, World!' }; resolve(data); }, 2000); }); }

async function getData() { try { const data = await fetchData(); console.log(data); } catch (error) { console.error('Error:', error); } }

getData();

In both examples, fetchData() simulates an asynchronous operation by returning a Promise that resolves with some data after a delay. The .then() method is used to handle the resolved value in the Promise chain, and the .catch() method is used to handle any errors that may occur.

With async/await, you use the async keyword to define a function that can await asynchronous operations. Inside an async function, you can use the await keyword to pause the execution of the function until the Promise is resolved or rejected, making the code look more synchronous and easier to read.