node.js - 是否可以从 .then 函数导出数据?
问题描述
我正在使用 mssql 模块处理 Node 和 MSSQL Server。使用 Promise 时,我想从 .then 函数导出或返回数据。这是可能的还是有任何解决方法?
getDb = function(){
// This code establishes connection to SQL Server
const conn = new sql.ConnectionPool(dbConfig);
const req = new sql.Request(conn)
conn.connect()
.then(function getData (req) {
// This code makes query to SQL Server
req.query("SELECT * FROM USER")
.then(function(res){
console.log(res) // logs Correct User
module.exports.user = res // logs undefined in main.js
})
.catch((err) => console.log(err))
}
)
.catch(function (err) {
console.log(err);
});
}
getDb()
任何帮助是极大的赞赏!
解决方案
这是一种简单的方法,您可以导出 getDb 函数并将其导入并使用到数据中:
exports.getDb = () => {
return new Promise((resolve, reject) => {
const conn = new sql.ConnectionPool(dbConfig);
const req = new sql.Request(conn)
conn.connect().then(req => {
return req.query("SELECT * FROM USER")
}).then(res => {
return resolve(res);
}).catch(err => {
console.log(err)
})
})
}
推荐阅读
- three.js - A字架| 滑杆
- python - 检索 mongodb 集合中所有文档的特定字段
- python - 熊猫:比较日期时间数组上的日期时间列
- python - 获取 statsmodel RollingOLS 结果汇总信息
- python - 如何读取和合并两个 CSV 文件
- operating-system - 信号量示例
- vb.net - 当应用程序失去焦点时将焦点分配给应用程序控制
- mongodb - 当你添加一个新的mongodb副本时,你怎么知道它什么时候赶上了master?
- reactjs - 根据状态动态地将组件添加到反应页面
- html - 光标位置不在 Microsoft Edge 中 contentEditable div 中占位符的开头