AshClarke
AshClarke

Reputation: 3078

Callback inside nested function

I'm trying to understand this code

I have simplified it with the code below and trying to understand how to use this function with a callback.

function test(text, callback) {
  function test2() {
    callback(text);
  }
}

And call it with

test('sometext', function(response) { 
  console.log(response);
});

However test2 never gets called.

How can I call test2 with this callback?

Upvotes: 4

Views: 1477

Answers (3)

Matt Ellen
Matt Ellen

Reputation: 11592

You need to call text2. All you do at the moment is define it. There are various ways you could do this. The simplest is to call the function where it is:

function test(text, callback) {
  (function test2() {
    callback(text);
  })();
}

Note the (); at the end of the definition and the parentheses around it. This will call test2 when test is run.

Another way to do the same thing is to call it after defining it:

function test(text, callback) {
  function test2() {
    callback(text);
  }
  test2();
}

Alternatively, you can use test as a factory for test2 and return it and call it at a later date:

function test(text, callback) {
  return function test2() {
    callback(text);
  }
}

var f = test('logged', console.log);

f();

In the example you link to it is not clear to me how the callback is called because it doesn't look like getTokenAndXhr is ever called. Perhaps there is some magic going on in the chrome browser that calls it via reflection of somekind.

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78535

You never call test2, only declare it. Execute it explicitly:

function test(text, callback) {
    function test2() {
      callback(text);
    }
    test2();
}

Or since functionally there is no reason to declare a scoped function like this, just trigger the callback:

function test(text, callback) {
    callback(text);
}

Upvotes: 1

Quentin
Quentin

Reputation: 943568

You have to actually call test2.

You could put a call to it directly inside test. You could return test2 and then call that return value later. etc.

Upvotes: 0

Related Questions