YouTip LogoYouTip

Nodejs Async Await

In Node.js, `async/await` is syntactic sugar for handling asynchronous operations. `async/await` is based on Promise, but makes asynchronous code look more like synchronous code, greatly improving code readability and maintainability. The `async` keyword is used to declare that a function is asynchronous, while the `await` keyword is used to wait for a Promise to resolve or reject. Using `async/await` can avoid callback hell and make error handling more intuitive. !(#) JavaScript is single-threaded. When encountering asynchronous tasks (such as setTimeout or network requests), it hands them over to the browser API for processing. After completion, the callback is placed in the message queue. The event loop continuously checks if the call stack is empty. If so, it takes the callback from the queue and pushes it onto the call stack for execution. This prevents blocking the main thread while processing asynchronous results in order. * * * ## Basic Syntax ### async Function Any function can become an asynchronous function by adding the `async` keyword: async function myFunction(){ return"Hello World"; } `async` functions always return a Promise. If the return value is not a Promise, it will be automatically wrapped into a Promise. ### await Expression `await` can only be used inside `async` functions. It pauses function execution, waits for the Promise to resolve, then continues execution and returns the result: async function fetchData(){ const response = await fetch('https://api.example.com/data'); const data = await response.json(); return data; } * * * ## Error Handling ### try/catch Method The most common way to handle `async/await` errors is using `try/catch`: ## Example async function getUser(){ try{ const response = await fetch('https://api.example.com/user'); const user = await response.json(); return user; }catch(error){ console.error('Error fetching user:', error); throw error;// Can choose to re-throw the error } } ### Direct Promise Handling You can also directly handle the returned Promise: ## Example getUser() .then(user => console.log(user)) .catch(error => console.error(error)); * * * ## Practical Application Examples ### Parallel Execution of Multiple Asynchronous Operations Using `Promise.all` combined with `async/await` can execute multiple asynchronous operations in parallel: ## Example async function fetchMultipleUrls(urls){ try{ const requests = urls.map(url => fetch(url)); const responses = await Promise.all(requests); const data = await Promise.all(responses.map(r => r.json())); return data; }catch(error){ console.error('Error fetching data:', error); throw error; } } ### Database Operation Example ## Example async function getUserAndPosts(userId){ try{ const user = await User.findById(userId); const posts = await Post.find({ userId }); return{ user, posts }; }catch(error){ console.error('Database error:', error); throw error; } } * * * ## Best Practices 1. **Always handle errors**: Don't ignore errors that `await` might throw, use `try/catch` or `.catch()` to handle them 2. **Avoid unnecessary await**: If you don't need to wait for the result, you can return the Promise directly 3. **Use parallelism reasonably**: Multiple independent asynchronous operations should be executed in parallel (using `Promise.all`) 4. **Keep code clear**: Avoid overly deep `async/await` nesting, extract functions when necessary 5. **Pay attention to performance impact**: Each `await` pauses function execution, be especially careful in loops * * * ## Common Questions ### Relationship between async/await and Promise `async/await` is syntactic sugar built on top of Promise. Any `async` function returns a Promise, and anything after `await` can be a Promise. ### Why does my async function return undefined? This may be because you forgot to use `return` before `await`, or the function exited before the Promise resolved. ### Can await be used at the top level? In ES modules (files ending with `.mjs` or `"type": "module"` in `package.json`), you can use `await` directly at the top level. In CommonJS modules, it needs to be wrapped in an `async` function. ## Example // In ES modules const data = await fetchData(); console.log(data);
← Nodejs VscodeNodejs Asynchronous β†’