Fix the Bug in Advanced Asynchronous Array Processing Function
Identify and fix the bug in the asynchronous function that processes an array of URLs to fetch JSON data and extract specific fields. The current implementation leads to incorrect results and unhandled errors.
Challenge prompt
You are given a broken asynchronous JavaScript function `fetchAndExtract` that accepts an array of URLs and a key string. It should fetch JSON data from each URL, extract the value corresponding to the given key, and return an array of those values. The function is intended to process requests in parallel but currently returns incorrect results or throws unhandled errors. Identify and fix the issues to make sure it works reliably with proper error handling and returns the extracted values in the same order as the input URLs.
Guidance
- • Check how asynchronous promises are created and handled within the function.
- • Ensure the function handles errors gracefully for failed fetches without breaking the whole operation.
- • Make sure the values are returned in the same order as the input URLs regardless of fetch response times.
Hints
- • Look carefully at how Promise.all and async/await are used; mixing them improperly can cause bugs.
- • Consider wrapping each fetch in a try-catch block or using Promise.allSettled for robust error handling.
Starter code
async function fetchAndExtract(urls, key) {
const results = [];
urls.forEach(async (url) => {
const response = await fetch(url);
const data = await response.json();
results.push(data[key]);
});
return results;
}Expected output
For input urls ['https://api.example.com/user/1', 'https://api.example.com/user/2'] and key 'name', the function should return ['Alice', 'Bob'] (assuming those are the names in the fetched JSON data).
Core concepts
Challenge a Friend
Send this duel to someone else and see if they can solve it.