Stack Overflow Asked on December 25, 2021
Hello I have a function like this:
let findOne = async function() {
return "hello"
}
module.exports = findOne()
I get to export it and use it in another script easily like this:
const findOne = require('../public/javascripts/data')
findOne.then(function (result) {
console.log(result)
})
Now I would like to do the same with another function in the same script as the first one but this time I would like it to have parameters:
let deleteOne = async function (id) {
return id+10
}
module.exports = deleteOne()
In other script :
const deleteOne = require('../public/javascripts/data')
deleteOne(5).then(function (result) {
console.log(result)
})
How I can do that ?
Just export the variable, in this case a function.
Example with commonJS
index.js
let findOne = async function() {
return 'Hello';
}
let deleteOne = async function(id) {
return id;
}
module.exports = {
findOne,
deleteOne,
}
test.js
const { findOne, deleteOne } = require('./index.js');
async function test() {
const x = await findOne();
const y = await deleteOne(5);
console.log(x, y);
}
test();
Answered by coder123 on December 25, 2021
You have exported as,
module.exports = deleteOne();
By assigning as above, you are exporting the value returned from executing the function. You should export only function reference as below.
module.exports = deleteOne;
Corrected code:
Exporting deleteOne:
let deleteOne = async function (id) {
return id+10
}
module.exports = deleteOne;
Importing deleteOne:
const deleteOne = require('../public/javascripts/data')
deleteOne(5).then(function (result) {
console.log(result)
})
Answered by vbrin27 on December 25, 2021
if you want to have both functions in one file and export them you can do it like this
Export File:
let findOne = async function() {
return "hello"
}
let deleteOne = async function (id) {
return id+10
}
module.exports = {findOne, deleteOne}
in other Script:
const {findOne, deleteOne} = require('../public/javascripts/data')
findOne().then(function (result) {
console.log(result)
})
deleteOne(5).then(function (result) {
console.log(result)
})
Answered by Andre on December 25, 2021
Your export is wrong. What you have is
module.exports = findOne()
- This will call the function and export the result, which is a Promise.
To export the function itself, don't call it:
module.exports = findeOne
To export multiple functions in the same script, give them a name in the export (export an object that contains the functions):
module.exports = { findOne, deleteOne };
And import them with their name:
const { findOne } = require('<path>')
Answered by Pasukaru on December 25, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP