[Go to site: main page, start]

0% found this document useful (0 votes)
2 views6 pages

Asynchronous JavaScript and Promises

The document provides a series of exercises focused on understanding promises in JavaScript, including creating promises, chaining them, handling rejections, and using async/await. It covers practical examples such as simulating API calls, implementing timeouts, and using Promise.all() and Promise.race(). These exercises aim to enhance the reader's grasp of asynchronous programming in JavaScript.

Uploaded by

Sweety Sonia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Asynchronous JavaScript and Promises

The document provides a series of exercises focused on understanding promises in JavaScript, including creating promises, chaining them, handling rejections, and using async/await. It covers practical examples such as simulating API calls, implementing timeouts, and using Promise.all() and Promise.race(). These exercises aim to enhance the reader's grasp of asynchronous programming in JavaScript.

Uploaded by

Sweety Sonia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Asynchronous JavaScript and Promises

1. Basic Promise Example


Create a promise that simulates fetching data from a server. It should resolve after 2 seconds
with a message "Data fetched successfully".
// Exercise 1: Create a promise that resolves after 2 seconds
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data fetched successfully");
}, 2000);
});

// Use `.then()` to log the result when the promise resolves


[Link]((message) => {
[Link](message); // Expected output: "Data fetched successfully"
});
2. Chaining Promises
Chain two promises. The first promise resolves with a number, and the second promise
should multiply the number by 2.
// Exercise 2: Chaining Promises
const numberPromise = new Promise((resolve, reject) => {
resolve(5);
});

numberPromise
.then((number) => {
return number * 2; // Multiply the number by 2
})
.then((result) => {
[Link](result); // Expected output: 10
})
.catch((error) => {
[Link](error);
});
3. Handling Promise Rejection
Create a promise that simulates an error by rejecting with a message "Something went
wrong!". Handle the rejection using .catch().
// Exercise 3: Handling Promise Rejection
const fetchDataWithError = new Promise((resolve, reject) => {
reject("Something went wrong!");
});

fetchDataWithError
.then((message) => {
[Link](message); // This won't be called
})
.catch((error) => {
[Link](error); // Expected output: "Something went wrong!"
});
4. Async/Await
Rewrite the above example using async/await instead of .then() and .catch().
// Exercise 4: Using async/await with a promise
async function getData() {
const fetchDataWithError = new Promise((resolve, reject) => {
reject("Something went wrong!");
});

try {
const result = await fetchDataWithError;
[Link](result); // This won't be called
} catch (error) {
[Link](error); // Expected output: "Something went wrong!"
}
}

getData();
5. Simulating Multiple API Calls with [Link]()
Simulate two API calls using promises: one that resolves after 1 second and another after 3
seconds. Use [Link]() to wait for both promises to resolve and log the results.
// Exercise 5: Using [Link]
const apiCall1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("API Call 1 completed"), 1000);
});

const apiCall2 = new Promise((resolve, reject) => {


setTimeout(() => resolve("API Call 2 completed"), 3000);
});

[Link]([apiCall1, apiCall2])
.then((results) => {
[Link](results); // Expected output: ["API Call 1 completed", "API Call 2 completed"]
})
.catch((error) => {
[Link](error);
});
6. Simulating Multiple API Calls with [Link]()
This time, use [Link]() to simulate two API calls. The promise that resolves first
should be logged.
// Exercise 6: Using [Link]
const apiCall1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("API Call 1 completed"), 2000);
});

const apiCall2 = new Promise((resolve, reject) => {


setTimeout(() => resolve("API Call 2 completed"), 1000);
});

[Link]([apiCall1, apiCall2])
.then((result) => {
[Link](result); // Expected output: "API Call 2 completed"
})
.catch((error) => {
[Link](error);
});
7. Implementing Timeout with Promises
Create a function that simulates a timeout using promises. If a task takes more than 3
seconds, it should reject with the message "Timeout!". If it completes in less than 3 seconds,
it should resolve with "Task completed".
// Exercise 7: Implementing Timeout with Promises
function taskWithTimeout() {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
reject("Timeout!");
}, 3000); // Timeout after 3 seconds

// Simulate a task that takes 2 seconds


setTimeout(() => {
clearTimeout(timeout);
resolve("Task completed");
}, 2000); // Task completed after 2 seconds
});
}

taskWithTimeout()
.then((message) => {
[Link](message); // Expected output: "Task completed"
})
.catch((error) => {
[Link](error); // This won't be called
});
8. Using async/await with [Link]()
Now, using async/await, simulate two API calls and use [Link]() to wait for both of them
to complete.
// Exercise 8: Using async/await with [Link]
async function fetchApiData() {
const apiCall1 = new Promise((resolve) => setTimeout(() => resolve("API Call 1
completed"), 1000));
const apiCall2 = new Promise((resolve) => setTimeout(() => resolve("API Call 2
completed"), 2000));

try {
const results = await [Link]([apiCall1, apiCall2]);
[Link](results); // Expected output: ["API Call 1 completed", "API Call 2 completed"]
} catch (error) {
[Link](error);
}
}

fetchApiData();

Bonus Challenge: Fetch Data and Handle Multiple Responses


Simulate fetching user data from an API and post data from an API. Use [Link]() to wait
for both requests and log the results.
// Exercise Bonus: Handling Multiple API Calls
const fetchUserData = new Promise((resolve) => {
setTimeout(() => resolve("User data fetched"), 1500);
});

const fetchPostData = new Promise((resolve) => {


setTimeout(() => resolve("Post data fetched"), 1000);
});

[Link]([fetchUserData, fetchPostData])
.then((results) => {
[Link](results); // Expected output: ["User data fetched", "Post data fetched"]
})
.catch((error) => {
[Link](error);
});

These exercises will give you a solid understanding of how promises work in JavaScript and
how to handle asynchronous code in various situations. Let me know if you'd like more
exercises or explanations!

You might also like