Trigger callback after getting multiple json files asynchronously
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
When fetching multiple JSON files in JavaScript, you often need to wait for all requests to complete before running a callback. The standard approach is Promise.all(), which takes an array of promises and resolves when every promise has resolved, giving you all results at once. Before Promises, developers used manual counters or libraries like async.js. Modern JavaScript also provides async/await with Promise.all() for clean, readable code. The key concept is coordinating multiple asynchronous operations and running a single callback only after all have finished.
Promise.all with fetch
Promise.all() runs all fetch requests concurrently and waits for every one to complete. The results array matches the order of the input promises, regardless of which request finishes first.
async/await with Promise.all
Using async/await with Promise.all() keeps the parallel execution benefit while making the code read sequentially. The two-step pattern (fetch all, then parse all) allows you to check HTTP status codes before parsing.
Manual Counter Pattern (Pre-Promise)
This pattern uses a counter that decrements on each successful load. The callback fires when the counter reaches zero. Promise.all() replaces this pattern entirely.
Promise.allSettled for Partial Failures
Promise.allSettled() waits for all promises to complete but does not reject on failure. Each result has a status of either "fulfilled" or "rejected". Use this when some requests are optional and you want the rest to succeed.
Loading JSON with jQuery
Dynamic Number of Files
Common Pitfalls
- Using
Promise.allwhen any request can fail:Promise.allrejects immediately when any single promise rejects, discarding all other results. If some requests are optional, usePromise.allSettled()to get results from the requests that did succeed. - Sequential awaiting instead of parallel: Writing
const a = await fetch(url1); const b = await fetch(url2);runs requests one after another. UsePromise.all([fetch(url1), fetch(url2)])to run them concurrently. Sequential fetching can be 2-5x slower. - Assuming fetch rejects on HTTP errors:
fetch()only rejects on network failures, not on 4xx or 5xx responses. Always checkresponse.okorresponse.statusbefore callingresponse.json(). A 404 response will attempt to parse the error page as JSON and fail. - Not handling JSON parse errors: If the server returns invalid JSON (e.g., an HTML error page),
response.json()throws aSyntaxError. Wrap the parse in a try-catch or validate theContent-Typeheader first. - Forgetting that Promise.all result order matches input order: Results from
Promise.allalways match the order of the input array, not the order in which requests completed. This is reliable for destructuring:const [a, b, c] = await Promise.all([fetchA, fetchB, fetchC]).
Summary
- Use
Promise.all()to fetch multiple JSON files in parallel and wait for all to complete - Use
async/awaitwithPromise.all()for readable, sequential-looking parallel code - Use
Promise.allSettled()when some requests are optional and partial failure is acceptable - Always check
response.okbefore parsing —fetch()does not reject on HTTP errors - Results from
Promise.all()maintain the same order as the input promises
Related reading
- Trying to call Async method synchronously. It waits on Task.Result forever
- Trying to implement a SIMPLE promise in Reactjs
- Turning an ExecutorService to daemon in Java
- Twisted Python - Two looping calls, one not firing according to given interval
- Trim string in JavaScript
- Turning off eslint rule for a specific file
- two distributed rendering contexts - synchronization
- Two instances of application connected to same, altered database
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.