0

I have this code snippet, where the callback only works when I define an anonymous function.

I wonder why sending res.send() function as a callback doesn't work? Shouldn't it work the same as the anonymous function? Like .then() should pass the argument to res.send() and call it.

What am I missing here?

const create = (req, res) => {
    // This works.
    Driver.create(req.body).then((driver) => res.send(driver));

    // This doesn't work!
    Driver.create(req.body).then(res.send);
};
aldokkani
  • 853
  • 1
  • 8
  • 17
  • 1
    Because `send` is a **method**, it cares what `this` is when you call it. When you do `.then(res.send)`, it'll get called with `this` set to the default value (`undefined` in strict mode, the global object in loose mode). You can fix that with `bind`: `.then(res.send.bind(res))` but to me the arrow function is clearer. – T.J. Crowder Aug 27 '20 at 15:40
  • (Note that none of this has anything to do with whether the callback is anonymous or not.) – T.J. Crowder Aug 27 '20 at 15:41

0 Answers0