0

I've been dipping my feet into javascript and more specifically node.js but I'm having trouble identifying required parameters for callbacks.

For example, when creating a route through Express, I can have the following

app.get('/', function() {
  console.log('this is a route');
});

Which will execute without giving me any trouble. However, having seen multiple examples, I know that I probably want to have something more along the lines of

app.get('/', function(req, res) {
  res.render('index');
});

But without having seen examples or documentation (which is sometimes just a couple unclear examples) is there a consistent way to determine what parameters a callback is expected to have?

I hope I've been clear.

3
  • 2
    Look at a method's documentation, and it will (almost always) tell you. Commented Oct 27, 2018 at 0:00
  • @CertainPerformance Yes, as I mentioned, I am interested in those cases for which documentation is unclear. Is there a debugging tool to aid in this case? Commented Oct 27, 2018 at 0:03
  • 1
    I suppose, think about the method and consider whether the callback seems necessary or not. If it doesn't seem necessary, leave it out and see if you can achieve your goal without it. Often, actually required parameters will throw an error when missing. Commented Oct 27, 2018 at 0:05

2 Answers 2

1

Without documentation, or inspecting the source of the function executing the callback, you wont easily know.

However, you can intercept them with some exploratory code and see what you get:

app.get('/', function() {
  console.log(arguments);
});

The arguments keyword here is the list of arguments passed to the callback function, so this will let you see what you got. If it tell you something is a Express.Request or something, this at least lets you know what to try to find in the docs.


But outside of standard javascript, using typescript or flow helps with this since it adds static types to javascript. If this function is typed, then your editor will then know arguments the callback function expects and can help you fill them in.

Sign up to request clarification or add additional context in comments.

Comments

0

Since you're using Express, the documentation is pretty clear - It depends on your route parameters and whether or not you're using middleware. There is no hard and fast rule, it genuinely depends on your route's function.

Your first example "works" because you're only printing to the console, but without the res response object you'll notice that that the request response returns nothing.

Start with req and res for each and expand as needed.

1 Comment

I was merely using Express as an example. I know it is well documented.

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.