Does top-level await work in JavaScript?
Yes, in ES modules (ES2022). In CommonJS or older browsers, await must be inside an async function. Wrap your code in an async function and call it: async function main() { ... } main();
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Common async/await Mistakes in JavaScript
Sequential await for independent operations (use Promise.all), using await in forEach (use for...of), forgetting try/catch (unhandled rejections), not awaiting (fire and forget), top-level await in old environments, and returning Promise.resolve from an async function (unnecessary).
Because forEach does not await the async callback. The loop finishes immediately, and the async callbacks run in parallel in the background. Use for...of for sequential await or Promise.all with map for parallel.
Use Promise.all: const [a, b] = await Promise.all([fetchA(), fetchB()]). Start all promises at once, then await all. This is much faster than sequential await for independent operations.
Still have questions?
Browse all our FAQs or reach out to our support team
