在Node.js中使用Exports从函数中的函数返回值 [英] Using exports in nodejs to return a value from function in a function
问题描述
我一直在阅读有关模块化代码的内容,并决定将一些函数导出到单独的文件中,并在调用它们后将其包含在我的主函数中.如果我调用它,只有我的网站配置不会返回:
I've been doing some reading on modularizing my code and decided to export some functions to a separate file and include them in my main function once it's called. Only my config of my website is not returning if I'm calling it:
// Export from my controller
// File: Controller.js
exports.site_config = function(company, data) {
siteConfig.find({"company" : company}, function data (err, siteConfig, data) {
// Console.log(siteConfig[0]) // Works
return siteConfig[0] // This return is not working
})
// Only here returns works....
}
// File: Index.js
const siteController = require('../controllers/site');
console.log(siteController.site_config('company2')) // nothing return
推荐答案
This is a special case of this problem. Synchronous code can be transformed to asynchronous but not vice versa.
Mongoose长期以来一直支持promises,回调API是旧的.这是他们的用例.
Mongoose has been supporting promises for a long time, callback API is legacy. This is a use case for them.
模块应导出配置对象的Promise.检索单个文档的更简洁方法是findOne
:
A module should export a promise of configuration object. A more concise way to retrieve a single document is findOne
:
exports.site_config = function(company, data) {
return siteConfig.findOne({"company" : company});
};
并被当作诺言消费.应该有一个promise链,如果需要,可以到应用程序入口点:
And is consumed as a promise. There should be promise chain, up to to application entry point if needed:
// inside `async` function:
const siteController = require('../controllers/site');
const config = await siteController.site_config('company2');
这篇关于在Node.js中使用Exports从函数中的函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!