New to ES6 here. I have a function declared “inside” a constant:
JavaScript
x
6
1
const requestData = https.request(source, function (res) {
2
3
<function code>
4
5
});
6
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:
JavaScript
1
10
10
1
const myCallback = (res) => {
2
3
<function code>
4
5
}
6
7
const requestData = https.request(source, myCallback);
8
9
myCallback( whatever );
10