0
function nestedFunction() {
  console.log('nested function');
}
function firstFunction(cb) {
  cb(nestedFunction());
}

function resetRouter() {
  setTimeout(() => {
    console.log('hello');
    firstFunction(() => {
      console.log('inside oye oyr');
    });
  }, 1000);
}

resetRouter();

This is my function . In this first reset Router is executed. Inside resetRouter after 1 second my first function is getting executed. First function takes a callback function as a param . Till here the things are clearer to me. But when the firstFunction is getting called it recieves a cb as a param , we are executing the callBackfunction and inside that callback function we are passing the nested function . So here first our nested function gets executed then the cb(callBack gets executed). So how is this being executed. Please someone explain its execution in a more clearer and easy way.

2 Answers 2

1
function firstFunction(cb) {
  cb(nestedFunction());
}

You're not passing nestedFunction. You're passing the value resulting from invoking nestedFunction (see the () after it). If you just want to pass a reference to nestedFunction into cb, just pass the name.

function firstFunction(cb) {
  cb(nestedFunction);
}
Sign up to request clarification or add additional context in comments.

Comments

1

This is what happens:

1: resetRouter gets called.
2: In 1 second:
   a. resetRouter logs "hello" in the console.
   b. call `firstFunction` with the argment - () => console.log("inside oye oyr")
      note: the callback function doesn't get executed in this step.

   c. nestedFunction gets called.
   d. nestedFunction logs "nested function"
   e. the callback in `b` gets called with one argument - undefined
   f. finally, `b` logs "inside oye oyr" in the console.

Output:

hello           // from resetRouter
nested function // from nestedFunction
inside oye oyr  // from firstFunction callback.

Comments

Your Answer

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.