Error-first callback convention in Node.js
📖 Scenario: You are building a simple Node.js module that reads user data from a pretend database. You want to follow the common Node.js pattern called the error-first callback convention. This means your functions will pass an error as the first argument to the callback if something goes wrong, or null if everything is fine.
🎯 Goal: Create a function called getUserData that takes a userId and a callback. The function should simulate fetching user data. If the userId is not found, call the callback with an error as the first argument. If found, call the callback with null as the error and the user data as the second argument.
📋 What You'll Learn
Create an object called
users with exactly these entries: 1: {name: 'Alice', age: 25}, 2: {name: 'Bob', age: 30}, 3: {name: 'Charlie', age: 35}Create a variable called
notFoundError that holds a new Error with the message 'User not found'Write a function called
getUserData that takes userId and callback parametersInside
getUserData, check if userId exists in users. If not, call callback(notFoundError). If yes, call callback(null, userData) with the user dataExport the
getUserData function using module.exports💡 Why This Matters
🌍 Real World
Many Node.js modules and libraries use the error-first callback pattern to handle asynchronous operations and errors clearly.
💼 Career
Understanding this pattern is essential for working with legacy Node.js code and many popular libraries that have not yet adopted promises or async/await.
Progress0 / 4 steps