Node.js nodejs-将查询结果导出到其他文件
我正在做一些查询以从数据库中检索一些数据,并尝试导出所述数据以用于我的nodejs应用程序。但到目前为止,我所尝试的一切都不起作用Node.js nodejs-将查询结果导出到其他文件,node.js,asynchronous,Node.js,Asynchronous,我正在做一些查询以从数据库中检索一些数据,并尝试导出所述数据以用于我的nodejs应用程序。但到目前为止,我所尝试的一切都不起作用 r.js async function site() { var test = await db .select("*") .from("site_credentials") .then(data => { return data; }); return test; } module.exports =
r.js
async function site() {
var test = await db
.select("*")
.from("site_credentials")
.then(data => {
return data;
});
return test;
}
module.exports = { user: site().then(data=>{return data})}
但我总是得到等待的承诺。即使在我进行导入时:
import users = require("./r")
users.then(data=>{return data})
但仍然不起作用。我怎样才能解决这个问题
谢谢,首先,没有理由解析承诺并立即返回在其then块中解析的相同对象。如果没有其他需要做的事情,就省略“then” 因此:
async function site() {
var test = await db
.select("*")
.from("site_credentials")
.then(data => {
return data; <--- this isn't necessary. Only adds noise unless there is something else you need to do. It's similar to "catching" and immediately "rethrowing" an error... just pointless
});
return test;
}
第二,我不太清楚您为什么要在导出中解决它。只需导出函数
module.exports = site;
然后,当您在应用程序的其他位置需要它时,请拨打电话并在那里解决:
const users = require("./r")
users.then(data=>{
// do something with your data here...
})
请注意,在第一个示例中,您正在导出一个对象,其中包含一个“users”属性,该属性是函数。如果这样做,则需要像这样调用它:
const users = require("./r")
users.users().then(data=>{
// do something with your data here...
})
你可以看到用户。用户显然没有意义。因此,适当出口以避免这种情况。仅导出函数本身,而不是嵌套在其他对象中
但是,如果你仔细观察,你会注意到我做错了另一件事。我正在导出一个“站点”功能,但要求它作为“用户”功能输入。命名约定很重要。如果这个函数在这里被称为“site”,您应该要求(或者根据您的模块加载器导入…)它作为“site”。。。因此:
否则,您只会把其他开发人员的crud弄糊涂。Yes;你不能欺骗async。@SLaks解决方法是什么?我的工作需要从数据库获取数据,我无法在本地保存凭据。您需要使所有内容都异步。谢谢@渣
const users = require("./r")
users.users().then(data=>{
// do something with your data here...
})
const site = require('./r');