2

I have a function that reads an http stream, combines the data events, and passes the response as a joined string. If I pass the 'data' event a function in the form of c => body.push(c) it works as expected. However, if I pass it body.push the content is never added to the array. Is there a reason generic prototypes can't be passed as parameters?

Here's my function:

const requestPromise = function(resolve, reject) {
    return (response) => {
        let body = [];

        response.on('data', body.push);
        response.on('end', () => {
            body = body.join('');
            if (body == "") {
                reject("Body is empty");
            } else {
                resolve(body);
            }
        });
    };
};
  • No, there is no reason that a prototype function "can't" be used as a higher-order function (ie. used as an argument to a function). The conclusion of "doesn't execute" is wrong as it *does* execute, just without the expected context. However, I would recommend reading up on how `this` is resolved in functions - as this (hah!) is crucial to understanding how ECMAScript works. Once understanding that, there is simply no question (above) left to answer. – user2864740 Aug 18 '17 at 20:53
  • See, perhaps: https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work/3127440 – user2864740 Aug 18 '17 at 20:57
  • While relevant to the answer, I don't think it's very clear that this was a scope issue; particularly since i never use the `this` keyword. – Ben Balentine Aug 24 '17 at 15:00

1 Answers1

2

push in that case is no longer has the calling context of body, so you had the right idea using an arrow function. Another possible approach is to explicitly bind() the method:

response.on('data', body.push.bind(body));
Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116