Complete the code to define a callback that handles an error first.
function callback([1], data) { if ([1]) { console.error('Error:', [1]); } else { console.log('Data:', data); } }
The first argument in an error-first callback is the error object, commonly named error.
Complete the code to call the callback with an error.
function fetchData(callback) {
const error = new Error('Failed to fetch');
callback([1], null);
}When there is an error, the first argument to the callback should be the error object.
Fix the error in the callback usage to follow the error-first convention.
function processData(callback) {
const data = { value: 42 };
callback([1]);
}
processData(function(err, data) {
if (err) {
console.error(err);
} else {
console.log(data.value);
}
});The callback should be called with null as the first argument to indicate no error, and the data as the second argument.
Fill both blanks to create an error-first callback that logs error or success message.
function handleResult([1], [2]) { if ([1]) { console.log('Error occurred:', [1]); } else { console.log('Success:', [2]); } }
The first parameter is the error (named error), and the second is the data (named data).
Fill all three blanks to define a function that calls a callback with error or data properly.
function getUser(id, [1]) { if (id <= 0) { [1](new Error('Invalid ID'), null); } else { const user = { id: id, name: 'Alice' }; [1](null, [2]); } }
The function uses callback as the callback name. It calls callback with an error or with user data.