0
0
Node.jsframework~10 mins

Error-first callback convention in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a callback that handles an error first.

Node.js
function callback([1], data) {
  if ([1]) {
    console.error('Error:', [1]);
  } else {
    console.log('Data:', data);
  }
}
Drag options to blanks, or click blank then click option'
Aerror
Bresult
Cresponse
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Using the data argument as the first parameter instead of the error.
Naming the first argument something unrelated like 'result'.
2fill in blank
medium

Complete the code to call the callback with an error.

Node.js
function fetchData(callback) {
  const error = new Error('Failed to fetch');
  callback([1], null);
}
Drag options to blanks, or click blank then click option'
Aundefined
Bnull
Cerror
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Passing null as the first argument when there is an error.
Passing false or undefined instead of the error object.
3fill in blank
hard

Fix the error in the callback usage to follow the error-first convention.

Node.js
function processData(callback) {
  const data = { value: 42 };
  callback([1]);
}

processData(function(err, data) {
  if (err) {
    console.error(err);
  } else {
    console.log(data.value);
  }
});
Drag options to blanks, or click blank then click option'
Anull, data
Bdata
Cundefined
Ddata, null
Attempts:
3 left
💡 Hint
Common Mistakes
Passing data as the first argument instead of the second.
Omitting the second argument when there is no error.
4fill in blank
hard

Fill both blanks to create an error-first callback that logs error or success message.

Node.js
function handleResult([1], [2]) {
  if ([1]) {
    console.log('Error occurred:', [1]);
  } else {
    console.log('Success:', [2]);
  }
}
Drag options to blanks, or click blank then click option'
Aerr
Berror
Cresult
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the order of error and data parameters.
Using inconsistent variable names.
5fill in blank
hard

Fill all three blanks to define a function that calls a callback with error or data properly.

Node.js
function getUser(id, [1]) {
  if (id <= 0) {
    [1](new Error('Invalid ID'), null);
  } else {
    const user = { id: id, name: 'Alice' };
    [1](null, [2]);
  }
}
Drag options to blanks, or click blank then click option'
Acallback
Buser
Cdata
Dresult
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the callback parameter.
Passing wrong variables to the callback.