Write a JS fetchAll function that concurrently fetches from an array of urls. The output…
- User
Write a JS fetchAll function that concurrently fetches from an array of urls. The output should be a result object of fulfilled array and rejected array.
Assistant
Here is an implementation of the fetchAll function:
async function fetchAll(urls) { const promises = urls.map(url => fetch(url).then(res => res.json())); const results = await Promise.allSettled(promises); const fulfilled = results.filter(r => r.status === 'fulfilled').map(r => r.value); const rejected = results.filter(r => r.status === 'rejected').map(r => r.reason); return { fulfilled, rejected }; } // Usage: const urls = [ 'https://api.github.com/users/john', 'https://api.github.com/invalid', 'https://api.github.com/users/jane' ]; fetchAll(urls).then(res => { console.log(res.fulfilled); // fulfilled responses console.log(res.rejected); // errors from rejected promises });The key aspects:
- Map each url to a fetch promise
- Wait for all promises to settle using
Promise.allSettled - Filter the results into fulfilled and rejected arrays
- Return object containing those arrays
This allows concurrent fetches and handling of both success and errors.
- User
Add the url to the rejected errors.
Assistant
Here is the updated fetchAll function that includes the url with the rejected errors:
async function fetchAll(urls) { const promises = urls.map(url => fetch(url).then(res => res.json())); const results = await Promise.allSettled(promises); const fulfilled = results.filter(r => r.status === 'fulfilled').map(r => r.value); const rejected = results.filter(r => r.status === 'rejected').map(r => ({ url: urls[r.reason.index], error: r.reason.error })); return { fulfilled, rejected }; } // Usage: fetchAll(urls).then(res => { console.log(res.rejected); // [{ url: 'https://api.github.com/invalid', error: FetchError }] });The key update is mapping over the rejected results and returning an object containing the url and error. The url comes from the original urls array at the index contained in the reason.
- User
reason.index? Does reason have an index?
Assistant
You're right, my previous example was incorrect. The reason object does not contain an index property. Here is an updated implementation:
async function fetchAll(urls) { const promises = urls.map((url, i) => fetch(url).then(res => ({res, index: i}))); const results = await Promise.allSettled(promises); const fulfilled = results.filter(r => r.status === 'fulfilled').map(r => r.value.res); const rejected = results.filter(r => r.status === 'rejected').map(r => ({ url: urls[r.value.index], error: r.reason })); return { fulfilled, rejected }; } // Usage: fetchAll(urls).then(res => { console.log(res.rejected); // [{ url: 'https://api.github.com/invalid', error: FetchError }] });The key differences:
- Map each url to an index value when creating the promises
- Include that index in the resolved value
- Then access the original urls array by that index
This allows linking the rejected result to the initial url without depending on the reason containing an index.
- User
List all the USA states by their abbreviation, not their full name.
Assistant
Here is an object mapping US state abbreviations to their 2 letter codes:
const states = { Alabama: 'AL', Alaska: 'AK', Arizona: 'AZ', Arkansas: 'AR', California: 'CA', Colorado: 'CO', Connecticut: 'CT', Delaware: 'DE', Florida: 'FL', Georgia: 'GA', Hawaii: 'HI', Idaho: 'ID', Illinois: 'IL', Indiana: 'IN', Iowa: 'IA', Kansas: 'KS', Kentucky: 'KY', Louisiana: 'LA', Maine: 'ME', Maryland: 'MD', Massachusetts: 'MA', Michigan: 'MI', Minnesota: 'MN', Mississippi: 'MS', Missouri: 'MO', Montana: 'MT', Nebraska: 'NE', Nevada: 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', Ohio: 'OH', Oklahoma: 'OK', Oregon: 'OR', Pennsylvania: 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', Tennessee: 'TN', Texas: 'TX', Utah: 'UT', Vermont: 'VT', Virginia: 'VA', Washington: 'WA', 'West Virginia': 'WV', Wisconsin: 'WI', Wyoming: 'WY' }; // Print abbreviations Object.values(states).forEach(abbr => { console.log(abbr); });To print just the abbreviations, I loop through the values of the states object using Object.values() and print each abbreviation.
- User
List the price of gas per state.
Assistant
Unfortunately I do not have access to current gas price data per state. However, here is an example of how that data could be structured if available:
const gasPrices = { AL: 3.45, AK: 3.89, AZ: 3.77, AR: 3.12, CA: 4.15, //... WY: 3.21 }; // Print gas prices Object.entries(gasPrices).forEach(([abbr, price]) => { console.log(`${abbr}: $${price}`); });This stores an object mapping state abbreviations to gas prices per gallon.
To print it, Object.entries() can be used to get both the abbreviation and price. Then we can print the prices in a nice formatted way:
AL: $3.45 AK: $3.89 AZ: $3.77 //...If actual up-to-date prices are needed, an API providing that data would need to be used to get the latest prices. But this shows how the prices could be stored and accessed by state abbreviation.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.