Today you will learn:
async/awaitPromise.all and Promise.raceBy the end, you will manage multiple async tasks efficiently.
Use async functions with await to get API data:
async function fetchData() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await res.json();
console.log(data);
} catch(err) {
console.log("Error:", err);
}
}
fetchData();
Run multiple promises in parallel:
const p1 = fetch("https://jsonplaceholder.typicode.com/todos/1").then(r => r.json());
const p2 = fetch("https://jsonplaceholder.typicode.com/todos/2").then(r => r.json());
const p3 = fetch("https://jsonplaceholder.typicode.com/todos/3").then(r => r.json());
// Wait for all
Promise.all([p1, p2, p3]).then(results => console.log(results));
// Wait for the fastest
Promise.race([p1, p2, p3]).then(result => console.log(result));
async function fetchData() {
try {
const res = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await res.json();
console.log(data);
} catch(err) {
console.log("Error:", err);
}
}
fetchData();
Complete the following:
Example:
async function fetchMultiple() {
const urls = [
"https://jsonplaceholder.typicode.com/todos/1",
"https://jsonplaceholder.typicode.com/todos/2",
"https://jsonplaceholder.typicode.com/todos/3"
];
try {
const promises = urls.map(url => fetch(url).then(r => r.json()));
const results = await Promise.all(promises);
console.log(results);
} catch(err) {
console.log("Network error:", err);
}
}
fetchMultiple();