0
0
Node.jsframework~10 mins

Callback pattern and callback hell 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 function that logs a message.

Node.js
function greet(name, [1]) {
  console.log('Hello ' + name);
  [1]();
}
Drag options to blanks, or click blank then click option'
Aevent
Bpromise
Casync
Dcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'promise' or 'async' as a parameter name instead of 'callback'.
Not calling the callback function inside the main function.
2fill in blank
medium

Complete the code to call a function with a callback that logs 'Done'.

Node.js
function doTask(cb) {
  setTimeout(() => {
    console.log('Task complete');
    [1]();
  }, 1000);
}
doTask(() => console.log('Done'));
Drag options to blanks, or click blank then click option'
Acb
Bcallback
Cdone
Dfinish
Attempts:
3 left
💡 Hint
Common Mistakes
Calling a function name not defined as a parameter.
Forgetting to call the callback function.
3fill in blank
hard

Fix the error in the nested callbacks to avoid callback hell.

Node.js
function step1(cb) {
  setTimeout(() => {
    console.log('Step 1');
    cb();
  }, 500);
}

function step2(cb) {
  setTimeout(() => {
    console.log('Step 2');
    cb();
  }, 500);
}

step1(() => {
  [1](() => {
    console.log('Step 3');
  });
});
Drag options to blanks, or click blank then click option'
Acallback
Bstep2
CsetTimeout
Dstep1
Attempts:
3 left
💡 Hint
Common Mistakes
Calling 'step1' again inside its own callback causing infinite loop.
Using undefined function names.
4fill in blank
hard

Fill both blanks to create a nested callback structure that logs steps in order.

Node.js
function first(cb) {
  setTimeout(() => {
    console.log('First');
    [1]();
  }, 300);
}

function second(cb) {
  setTimeout(() => {
    console.log('Second');
    [2]();
  }, 300);
}

first(() => {
  second(() => {
    console.log('Done');
  });
});
Drag options to blanks, or click blank then click option'
Acb
Bcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for callback parameters inconsistently.
Not calling the callback functions inside setTimeout.
5fill in blank
hard

Fill all three blanks to create a callback chain that logs three steps in order.

Node.js
function one(cb) {
  setTimeout(() => {
    console.log('One');
    [1]();
  }, 200);
}

function two(cb) {
  setTimeout(() => {
    console.log('Two');
    [2]();
  }, 200);
}

function three(cb) {
  setTimeout(() => {
    console.log('Three');
    [3]();
  }, 200);
}

one(() => {
  two(() => {
    three(() => {
      console.log('All done');
    });
  });
});
Drag options to blanks, or click blank then click option'
Acb
Bcallback
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing callback parameter names inconsistently.
Forgetting to call the callback in any function.