async functions return Promises; await pauses until a Promise settles. This is syntactic sugar over promises—but it reads like synchronous code, which helps HTTP handlers and scripts.
Basic pattern
async function loadConfig() {
const raw = await readFile('config.json', 'utf8');
return JSON.parse(raw);
}
Error handling
try {
const config = await loadConfig();
} catch (err) {
console.error('Failed to load config', err);
process.exit(1);
}
Top-level await
ESM modules allow await at top level—this playground uses it in main.mjs without wrapping in async main().
Important interview questions and answers
- Q: Does await block the thread?
A: It suspends the async function and yields to the event loop—other callbacks can run; it does not block the entire process like sync sleep. - Q: async without await?
A: Still returns a Promise—useful when returning promise chains from helpers.
Self-check
- What does an async function return if you return a plain number?
- Where should you catch errors from await?
Pitfall: Forgetting await returns a Promise object, not the resolved value—log shows Promise { <pending> }.
Interview prep
- try/catch with async?
Wrap
awaitin try/catch inside async functions—or use.catch()on the returned Promise at the call site.