I have function in unbound.js with the the following code
export default async function connect({ mongoose: mongoose }, URI) {
console.log('in connect');
mongoose.connect(URI);
mongoose.Promise = global.Promise;
});
}
I then have another index.js to deal with dependency injection which looks like this
module.exports = async url => {
return await require("./unbound").default.bind(
null,
{
mongoose: require("mongoose")
},
url
);
};
The only thing I am doing different to plain vanilla dependency injection is to pass the URL as an argument.
When I call the export from index.js
I get no response. This is confirmed by console.log
not outputting
Any guidance on how I could resolve this ?
Since chat restricted, I'm gonna post the answer here instead. In this snippet, you export a function
that when invoked, return another function
module.exports = async url => {
return await require("./unbound").default.bind(
null,
{
mongoose: require("mongoose")
},
url
);
};
So if you want to actually run it, you have to invoke it twice like require('./')()()
for example
As others have suggested, bind returns a bound function that you can call, it does not actually call the function - that is what .apply or .call does. @ptdien's solution is somewhat correct, but it won't work because you've forgotten to return the promise that mongoose.connect returns so your connect function returns undefined, so there is nothing the the caller to await. Ie you need to do this:
export default function connect({ mongoose: mongoose }, url) { mongoose.Promise = global.Promise; return mongoose.connect(url); }
(Also note that I've removed the async keyword as that is not necessary when we are not using await - the code returns a promise already.
Also, bind will automatically forward arguments after the bound ones (ie the url in this case), so you can simplify your code to this:
module.exports = require("./unbound").default.bind( null, { mongoose: require("mongoose") } );
By the way, the reason you have to append .default is because you are mixing node.js requires and ES6 imports. Pick one and stick to it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.