Performance: Async/await syntax
Async/await affects how JavaScript handles asynchronous operations, impacting input responsiveness and event loop efficiency.
Jump into concepts and practice - no test required
async function fetchData() { const response = await fetch('https://api.example.com/data'); const json = await response.json(); // process json // more code }
function fetchData() {
const data = fetch('https://api.example.com/data').then(response => response.json()).then(json => {
// process json
});
// more code
}| Pattern | Event Loop Blocking | Code Readability | Latency Impact | Verdict |
|---|---|---|---|---|
| Chained .then() Promises | No blocking | Harder to read | Moderate | [!] OK |
| Async/await Sequential | No blocking | Easy to read | High latency | [X] Bad |
| Async/await Parallel Promises | No blocking | Easy to read | Low latency | [OK] Good |
await keyword do inside an async function in Node.js?awaitawait keyword pauses the execution of the async function until the promise it waits for settles (resolves or rejects).async keyword before the function keyword.async function myFunc() {}. Others are invalid syntax.async function getNumber() {
return 42;
}
async function main() {
const result = await getNumber();
console.log(result);
}
main();getNumber is async and returns 42, which means it returns a promise that resolves to 42.mainawait keyword waits for the promise to resolve, so result gets the value 42, which is then logged.async function fetchData() {
const data = await fetch('https://api.example.com/data');
return data.json();
}
fetchData().then(console.log);data.json() returns a promise.data.json() returns a promise, it should be awaited to get the parsed JSON before returning.async function getUserAndPosts() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
return { user, posts };
} catch (error) {
console.error('Error fetching data:', error);
return null;
}
}fetchUser() first, then uses the user ID to await fetchPosts(), ensuring sequential execution.