Intermediate LevelVue JS
How does top-level await work inside <script setup> and why does it require <Suspense>?
❓ Interview Prompt: Explain top-level await in <script setup>, automatic async setup() compilation, and parent <Suspense> requirements.
Inside '<script setup>', Vue allows writing top-level 'await' statements directly: 'const data = await fetch("/api").then(r => r.json())'.
How Vue Compiles Top-Level Await:
When Vue encounters top-level 'await' inside '<script setup>', it automatically compiles the component's 'setup()' function into an async setup() function.
Requirement:
Any component with top-level 'await' MUST be wrapped in a parent '<Suspense>' component, or Vue will throw an error!
Code Implementation Example
html
<!-- AsyncUserProfile.vue -->
<script setup>
// Top-level await automatically makes setup() an async function!
const response = await fetch('/api/user/profile');
const profile = await response.json();
</script>
<template>
<div>User: {{ profile.name }}</div>
</template>💡Using top-level await in <script setup> (requires parent <Suspense>).
🎯 Interview Key Takeaway
Top-level await in <script setup> compiles setup into an async function, requiring a parent <Suspense> wrapper.
#top-level await#script setup#Suspense#Intermediate
Back to all Vue JS Questions→