Answer the question
In order to leave comments, you need to log in
How to write a function that returns data from a database?
You need to write a function that takes a SQL query string and returns an array of data received from the database. I only achieved that the data was output to the console inside the function, but I can’t figure out how to make the function return data. The code:
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const { request } = require('http');
const config = require('./config_db');
const connection = new Connection(config);
connection.on('connect', (err) => {err ? console.log(err) : select(query)});
const select = (query) => {
request = new Request(query);
request.on('row', (columns) => {
columns.map(column => {
console.log(column.value)
})
})
connection.execSql(request)
return request
};
module.exports = select;
const Connection = require('tedious').Connection;
const Request = require('tedious').Request;
const { request } = require('http');
const config = require('./config_db');
const addState = require('./state').addState; // функция делает push в state
const connection = new Connection(config);
connection.on('connect', (err) => {err ? console.log(err) : select(query)});
const select = (query) => {
request = new Request(query);
request.on('row', (columns) => {
columns.map(column => {
addState(column.value)
})
})
connection.execSql(request)
const state = require('./state').state // импортирую именно сдесь, потому что если импортировать раньше вернется пустой state
return state
};
module.exports = select;
Answer the question
In order to leave comments, you need to log in
const select = (query) => new Promise((resolve, reject) => {
const request = new Request(query);
request.once('error', reject);
request.once('done', (rowCount, more, rows) => {
resolve(rows.map(
columns => columns.map(
column => column.value
)
));
});
connection.execSql(request);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question