Reputation: 854
I have faced a problem regarding calling an exported function inside the same file.
When I call it then the error shows the following.
UnhandledPromiseRejectionWarning: ReferenceError: findOrCreateMedia is not defined
where findOrCreateMedia
is my function. How can I fix this?
Upvotes: 2
Views: 2495
Reputation: 187
This is happening because you are losing your this
object reference inside your calling function.
For eg:
module.exports.a = function () {
return true
}
module.exports.b = function() {
return this.a();
}
here you will get the issue because when you call this.a(), it is referencing the this
object of the b
function.
To solve this your have to store your this
object reference somewhere or use the arrow function, because the arrow function doesn't have there own this
object so it will always reference the outer this
object
To solve this, modify your function like this
module.exports.a = function () {
return true
}
module.exports.b = () => {
return this.a();
}
Upvotes: 1
Reputation: 11496
you can also ES6 import/export function:-
const someFunction = (){
...
}
export default someFuntion ( in the case on single function)
When you want to export multiple functions
export { someFunction1, someFunction2}.
Now the place where you want to import
import somFunction from 'filelocation' ( note in case of default exports you need to use the same name of the function)
In the case of multiple functions.You can change the function name but keep in mind the order of exports and imports.
import { myFunction1,myFunction2} from 'fileLocation'
Upvotes: 0
Reputation: 900
Try this:
function functionName() { ... };
exports.functionName = functionName;
functionName();
Upvotes: 1