我转而使用STREAM使用Node JS mssql繁琐的驱动程序。
箭头语法让我失去了大范围的时间范围和循环等......
我成功获取了第一个查询结果,然后将嵌套数据附加到它。然而这对我来说毫无意义
request.on('row', row => { // so "row" is object of data in scope but how to access?
console.log(row); // I see that I am giving it to spit out the records on each loop
obj = extend({}, row); // this was a hail mary move to try to copy the object from more of a global object declaration.
问题是request.on('row', row => {
是一个被隔离的循环:/
SOOO,我想要做什么返回完成" row" ...
我有这段代码
request.on('done', results => {
// this code cannot see "row"
before the arrow function etc... , I would return my data with
res.json(mydata); // how I did in the past
});
完整代码
(function () {
'use strict';
var sql = require('mssql');
var xconfig = require('../../config.js');
var newConfig = xconfig.database.liberty;
var extend = require('util')._extend;
exports.getLibScriptQuestions = function (connection, req, res) {
//console.log('conn',connection);
const poolLiberty = new sql.ConnectionPool(newConfig, err => {
var obj = "";
var responseData = [];
var request = new sql.Request(poolLiberty);
request.stream = true;
var query = 'SELECT * FROM ' +
' dbo.vwScriptQuestions vwsq';
request.query(query);
request.on('recordset', columns => {
// emit once
});
request.on('row', row => {
var requestOD = new sql.Request(poolLiberty);
requestOD.input('QuestionId', sql.Int, row.QuestionId);
var sqlquery = 'SELECT q.id AS QuestionId, d.* FROM ' +
' Scripts.Question q ' +
' JOIN Scripts.QustionDirectiveAssoc qda ON q.Id = qda.QuestionId' +
' JOIN Scripts.Directives d on qda.DirectiveId = d.Id ' +
' WHERE q.Id = @QuestionId';
requestOD.query(sqlquery, (err, result) => {
row.directives = result.recordset;
//console.log('row', row)
//console.log(row.directives[0].Tag);
obj = row.directives[0].Tag;
//obj.push(row.directives);
//obj = extend({}, row.directives);
responseData.push(row);
//console.log(result.recordset);
//console.log('directives',row.directives);
});
//console.log(row);
//
})
request.on('error', err => {
// May be emitted multiple times
console.log('err', err);
})
request.on('done', result => {
console.log('done x records', result);
console.log('request',request.query.recordsets);
console.log(responseData);
console.log('obj', obj)
//res.json(vm);
res.json(responseData);
})
})
sql.on('error', err => {
console.log('err happened', err);
})
}
}());
答案 0 :(得分:0)
看看这是否是你想要达到的目的。
let responseData = [];
request.on('row', row => {
responseData.push(row);
});
request.on('done', results => {
res.json(responseData);
});