Skip to content
Advertisement

What’s the best way to re-run a const-declared function?

New to ES6 here. I have a function declared “inside” a constant:

const requestData = https.request(source, function (res) {
   ...
   <function code>
   ...
});

I need to re-run this periodically. What’s the best way to do it? Simply calling requestData() is throwing ‘Type Error’ messages. Thanks!

Advertisement

Answer

The second argument to https.request is a function reference that is called with a single parameter, the result of the request.

If the function is created by a function expression in the call as in the OP, then you can’t reference it from any scope other than within the function itself, and only then if it’s been given a name.

If you want to call the function separately, you need to declare/assign it first in the scope you want to call it, then use it in the call. E.g. using an arrow function:

const myCallback = (res) => {
   ...
   <function code>
   ...
}

const requestData = https.request(source, myCallback);

myCallback( whatever );
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement