嗯,我是NodeJS的新手。虽然我有一些基础知识,但现在我对下面的代码有点困惑了。目标是创建一个可以执行给定SQL查询并返回其结果的公共模块。
问题非常清楚。我的方法返回的时间早于结果可能从SQL服务器返回。我试图以十几种方式解决它,但它们都没有奏效。如果有人能够解释我做错了什么以及使这段代码正常工作的正确方法,我真的很感激。
database \ config.js
module.exports = {
user: 'mssql',
password: 'mssql',
server: 'localhost',
database: 'mssql',
stream: true
};
database \ database.js
var sql = require('mssql');
var config = require('./config');
module.exports = function(query) {
var result = [];
sql.connect(config).then(function () {
var request = new sql.Request();
request.query(query);
request.on('row', function (row) {
result.push(row);
});
}).then(function() {
return result;
});
}
routes \ index.js
var express = require('express');
var router = express.Router();
var queries = require('../database/queries.json');
var database = require('../database/database');
router.get('/', function (req, res, next) {
res.render('index', {
books: database(queries.books)
});
});
module.exports = router;
答案 0 :(得分:0)
database
函数应该返回一个Promise对象,该对象在解析时将包含查询结果。为此,您不需要result
数组:
database \ database.js
module.exports = function(query) {
return sql.connect(config).then(function () {
var request = new sql.Request();
// Return the Promise object that will contain the result of
// the query when resolved
return request.query(query);
});
};
routes \ index.js
router.get('/', function (req, res, next) {
// The object returned after calling 'database' is the 'Promise'
// object that contains the result of the query.
database(queries.books).then(function(result) {
res.render('index', {
books: result
});
});
});