4

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?

asked Jun 18, 2014 at 7:26

3 Answers 3

2

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.

answered Jun 18, 2014 at 7:37
Sign up to request clarification or add additional context in comments.

Comments

1

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);
}
answered Jun 18, 2014 at 7:32

Comments

0

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.

answered Jun 18, 2014 at 7:31

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.