-2

This is the most basic Nested Callback I could think of, and it is giving me an error[posted below]

function a (callback) {
    console.log('first print a')
    callback()
}

function b (callback) {
    console.log('b after a')
    callback()
}

function c () {
    console.log('c after b')
}

a(b(c))

Output/Error -

b after a
c after b
first print a
/nodejs/file.js:33
callback()
^
TypeError: callback is not a function

d02d33pak
  • 673
  • 3
  • 8
  • 22
  • 3
    `b` isn't returning anything, which means `a` is being called with `undefined`. `a(undefined)` -> inside `a`, it tries to call `callback`, but `callback` is not a function - it's undefined. – CertainPerformance Jun 02 '18 at 07:19
  • but so isn't 'c', how come b's callback isn't returning any error – d02d33pak Jun 02 '18 at 07:22
  • 1
    Because you're not calling `c`, you're passing `c` as a parameter to `b` without calling it first. `a(b(c()))` *would* generate an error, because `c` doesn't return anything, resolving to `a(b(undefined))`. – CertainPerformance Jun 02 '18 at 07:23
  • oh, I think I get it now, since I'm passing b(c) to a - it thinks of it as a function that returns something... Am I right? – d02d33pak Jun 02 '18 at 07:24
  • 1
    Both `a` and `b` are followed by calling parenthesis, making `a(b(c))` evaluate the same as `var result = b(c); a(result);`. – Related: [Pass an extra argument to a callback function](https://stackoverflow.com/questions/40802071/pass-an-extra-argument-to-a-callback-function) – Jonathan Lonowski Jun 02 '18 at 07:24
  • Please avoid answering questions in comments. – supra28 Jun 02 '18 at 07:25
  • thank you very much, I get it now.. I'm new to Node.js and this had me going nuts – d02d33pak Jun 02 '18 at 07:26
  • `a(function() { b(function() { c() }) })` can anyone explain how this works for the same. – d02d33pak Jun 02 '18 at 15:09

1 Answers1

-1

You may use like this:

function a (callback) {
    console.log('first print a')
    return callback
}

function b (callback) {
    console.log('b after a')
    return callback
}

function c () {
    console.log('c after b')
}

a(b(c()))
supra28
  • 1,646
  • 10
  • 17
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231