0

I just started to learn Node Js then I got the following code in the tutorial

const readline = require("readline");

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

const questions = [
  "What is your name? ",
  "Where do you live? ",
  "What are you going to do with node js? "
];

const collectAnswers = (questions, done) => {
  const answers = [];
  const [firstQuestion] = questions;

  const questionAnswered = answer => {
    answers.push(answer);
    if (answers.length < questions.length) {
      rl.question(questions[answers.length], questionAnswered);
    } else {
      done(answers);
    }
  };

  rl.question(firstQuestion, questionAnswered);
};

collectAnswers(questions, answers => {
  console.log("Thank you for your answers. ");
  console.log(answers);
  process.exit();
});

The code has the following result

What is your name? a
Where do you live? b
What are you going to do with node js? c
Thank you for your answers.
[ 'a', 'b', 'c' ]

As far as I understand that the variable collectAnswer somehow inject the function declared below to the second parameter (done). Can someone explain what is actually happening behind the scene? How can the function declared below injected to the variable with the same name with it? Any term this pattern actually called?

9
  • done is one of its parameters. The caller provides a function as the argument. Commented Feb 2, 2022 at 15:58
  • it is calledcallback function, since Node.js is async in nature Commented Feb 2, 2022 at 15:59
  • 1
    @AbishekKumar This has nothing to do with asynchrony. It's like the callback to forEach(). Commented Feb 2, 2022 at 15:59
  • 1
    "How can the function declared below injected to the variable with the same name with it?" - What name are you talking about? Commented Feb 2, 2022 at 16:06
  • 1
    Thanks everyone, I just confuse myself because many arrow function and same variable name. I think collectAnswers(questions, answers =>{}) at the bottom is defining a new function, but it actually just calling the function defined before. T.J. Crowder has explain it pretty clear Commented Feb 2, 2022 at 16:12

1 Answer 1

2

Functions are objects in JavaScript, unlike some other languages, so you can pass them into functions as arguments and the functions can receive them as parameters. This is done a lot so that the function you're calling can "call back" to your code (the function you're passing in). A function used this way is often called a "callback." A function like collectAnswers that accepts a function it's going to call this way is often described as a function that "accepts a callback."

In that code, there's a function called collectAnswers and it accepts two parameters, questions and done:

const collectAnswers = (questions, done) => {
//                      ^^^^^^^^^−−^^^^−−−−−−−−−−−−−−−− parameters
    // ...
};

At the end, the code calls collectAnswers, passing in an array of questions and new function created inline as the second argument (I've put the two arguments on separate lines for clarity):

collectAnswers(
    questions,                                          // 1st argument

    answers => {                                        //
        console.log("Thank you for your answers. ");    //
        console.log(answers);                           // 2nd argument
        process.exit();                                 //
    }                                                   //
);

That does the same thing as this, except for the callback constant:

const callback = answers => {
    console.log("Thank you for your answers. ");
    console.log(answers);
    process.exit();
};
collectAnswers(questions, callback);
Sign up to request clarification or add additional context in comments.

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.