Complete the code to run two async functions one after another (sequentially).
async function runSequential() {
await fetchData1();
await [1]();
}To run async functions sequentially, you await each one in order. Here, after fetchData1(), you await fetchData2().
Complete the code to run two async functions in parallel and wait for both to finish.
async function runParallel() {
await Promise.[1]([fetchData1(), fetchData2()]);
}Promise.race waits only for the first promise to settle.Promise.any waits for the first fulfilled promise, not all.Promise.all runs multiple promises in parallel and waits for all to resolve.
Fix the error in the code to correctly run async functions sequentially.
async function run() {
await fetchData1();
[1] fetchData2();
}async keyword incorrectly inside the function body.To run async functions sequentially, you must await each call to pause until it finishes.
Fill both blanks to create a parallel async execution that handles errors gracefully.
async function runSafeParallel() {
const results = await Promise.[1]([
fetchData1(),
fetchData2()
]);
results.forEach(result => {
if (result.status === '[2]') {
console.log('Success:', result.value);
} else {
console.error('Error:', result.reason);
}
});
}Promise.all rejects immediately on any error.Promise.allSettled waits for all promises and returns their status. Checking for fulfilled lets you handle successes and errors separately.
Fill all three blanks to create a dictionary of results from parallel async calls filtering only successful ones.
async function getResults() {
const results = await Promise.[1]([
fetchData1(),
fetchData2(),
fetchData3()
]);
return results.reduce((acc, [2], index) => {
if ([3].status === 'fulfilled') {
acc[`data${index + 1}`] = [2].value;
}
return acc;
}, {});
}Promise.all which rejects on first error.Promise.allSettled returns an array of result objects. Using result as the variable name for each item, you check if result.status is 'fulfilled' to include only successful results.