Introduction
Async patterns let Node.js do many things at once without waiting. This keeps apps fast and smooth.
Jump into concepts and practice - no test required
Async patterns let Node.js do many things at once without waiting. This keeps apps fast and smooth.
async function example() { const result = await someAsyncTask(); console.log(result); }
async before a function to mark it as asynchronous.await inside async functions to wait for tasks without blocking.const fs = require('fs').promises; async function readFile() { const data = await fs.readFile('file.txt', 'utf-8'); console.log(data); }
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve('Done'), 1000);
});
}
async function run() {
const message = await fetchData();
console.log(message);
}This program reads a file named example.txt asynchronously. It prints the content if successful or an error message if not. The app does not freeze while waiting for the file.
import { readFile } from 'node:fs/promises'; async function showFile() { try { const content = await readFile('example.txt', 'utf-8'); console.log('File content:', content); } catch (error) { console.error('Error reading file:', error.message); } } showFile();
Async code helps Node.js handle many tasks without waiting for each to finish.
Always handle errors in async code using try/catch or .catch().
Using async patterns improves app speed and user experience.
Async patterns keep Node.js apps fast by not blocking tasks.
Use async and await to write clear async code.
They are essential for reading files, calling APIs, and handling many users.
async before the function keyword.async function myFunc() {}.async function fetchData() {
return 'data';
}
fetchData().then(console.log);
console.log('start');async function readFile() {
const data = fs.readFileSync('file.txt');
console.log(data);
}