What methods do you know for working with asynchronous code?
sobes.tech AI
Answer from AI
Callbacks, Promises, async/await.
Callbacks: Functions passed as arguments to other functions, called after an asynchronous operation completes.
Promises: Objects that provide a more convenient way to handle asynchronous operations compared to callbacks. They have states pending, fulfilled, and rejected.
// Example Promise
function asyncOperation() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Operation completed successfully!');
}, 1000);
});
}
asyncOperation()
.then(result => console.log(result))
.catch(error => console.error(error));
async/await: Syntactic sugar over Promises that makes asynchronous code look more like synchronous code and improves readability.
// Example async/await
async function performAsyncOperation() {
try {
const result = await asyncOperation();
console.log(result);
} catch (error) {
console.error(error);
}
}
performAsyncOperation();
Comparison of methods:
| Method | Readability / Maintainability | Error Handling | Flow Control |
|---|---|---|---|
| Callbacks | Less readable (Callback Hell) | Difficult | Difficult |
| Promises | Improved | Convenient (.catch) | Convenient (.then, .catch) |
| async/await | Best | Convenient (try...catch) | Convenient (await) |
The most preferred method in modern Node.js applications is using async/await due to its readability and convenience. Promises remain an important tool, especially at a lower level of implementation. Callbacks are used in legacy code or for low-level operations in the Node.js core.