Is it possible to export data from .then function? - node.js

I am working with Node and MSSQL Server using the mssql module. When consuming a promise, I would like to export or return data from the .then function. Is this possible or are there any workarounds?
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()
Any help is greatly appreciated!

Here is a simple way you can export the getDb function and import and consume it to the the data:
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)
})
})
}

Related

In node.js, why is my data not getting passed back after a asynchronous file read using a Promise

I know for sure that my pullData module is getting the data back from the file read but the function calling it, though it has an await, is not getting the data.
This is the module (./initialise.js) that reads the data:
const fs = require('fs');
const getData = () => {
return new Promise((resolve, reject) => {
fs.readFile('./Sybernika.txt',
{ encoding: 'utf8', flag: 'r' },
function (err, data) {
if (err)
reject(err);
else
resolve(data);
});
});
};
module.exports = {getData};
And this is where it gets called (app.js):
const init = require('./initialise');
const pullData = async () => {
init.getData().then((data) => {
return data;
}).catch((err) => {
console.log(err);
});
};
const start = async() => {
let data = await pullData();
console.log(data);
}
start();
putting 'console.log(data)' just before return(data) in the resolve part of the call shows the data so I know it's being read OK. However, that final console.log shows my data variabkle as being undefined.
Any suggestions?
It's either
const pullData = async () => {
return init.getData().then((data) => {
return data;
}).catch((err) => {
console.log(err);
});
};
or
const pullData = async () =>
init.getData().then((data) => {
return data;
}).catch((err) => {
console.log(err);
});
Both versions make sure a promise returned by then/catch is passed down to the caller.

node-postgres returning undefined result

When i try to get result from node-postgres from my express app, pool.query is returning undefined result when i log it in console. Not sure if its about database connected properly or I am not returning the result properly? I am using heroku to deploy the app and using connection string given by heroku. Cant figure it out, anyone there to help please?.
db.js:
const { Pool } = require('pg');
const conString = process.env.DATABASE_URL;
const pool = new Pool({
connectionString: conString,
ssl: {rejectUnauthorized: false}
});
module.exports ={
getResult: (sql, params, callback)=>{
pool.query(sql, [params], (error, results)=>{
console.log(results);
if(!error){
callback(results);
}else{
callback(null);
}
pool.end();
});
}
}
user-model.js
var db = require('./db');
module.exports ={
findUserById: (userId)=>{
return new Promise((resolve, reject)=>{
var sql = "select id from users where id=?";
db.getResult(sql, [userId], (result)=>{
if(result.length>0){
resolve(true);
}else{
resolve(false);
}
});
});
}
}
seems the sent query parameter is in mysql format, use node-postgres format which is var sql = "select id from users where id = $1"; which should return valid result
It seems that your use of params is not correct.
You're passing an array to db.getResult(), then using it as the first element of another array.
Should just be pool.query(sql, params, (error, results)=>{ on that line.
you need to get the pool connection
const pool = require('./pool');
module.exports = {
// my version
findUserById(sql, params) {
return new Promise((resolve, reject) => {
return pool
.connect()
.then(conn => {
conn
.query(sql, [params])
.then(result => {
conn.release()
resolve(result)
})
.catch(error => {
conn.release()
reject(error)
})
})
})
},
// your version
findUserByIds: (userId) => {
return new Promise((resolve, reject) => {
var sql = "select id from users where id=?";
db.getResult(sql, [userId], (result) => {
if (result.length > 0) {
resolve(true);
} else {
resolve(false);
}
});
});
}
}
//// in you main or you controller file
// use the function
const { findUserById } = require('./model')
app.get('/user/:id', (req, res) => {
let sql = 'select * from "users" where "userId"= $1';
findUserById(sql, 1)
.then(result => {
res.status(200).send({
data: result
})
})
.catch(error => {
res.status(400).send(error)
})
})

How can i access nested promise data?

I am trying to set up a route that sends data from a nested promise to my vue app.
But i'm having trouble with the getting data from the nested promises.
i tried using a callback with no success
app.get('/notification', (req, res) => {
const getData = (data) => {
console.log(data)
}
scheduler(data)
})
const scheduler = (callback) => {
sftp
.connect({ credentials })
.then(() => {
return sftp.list(root);
})
.then(async data =>
{
const filteredFile = data.filter(file => {
let currentDate = moment();
let CurrentTimeMinusFive = moment().subtract(5, "minutes");
let allAccessTimes = file.accessTime;
let parsedAccessTimes = moment(allAccessTimes);
let filteredTime = moment(parsedAccessTimes).isBetween(
CurrentTimeMinusFive,
currentDate
);
return filteredTime;
});
for (const file of filteredFile) {
let name = file.name;
let filteredThing;
await sftp
.get(`Inbound/${name}`)
.then(data => {
csv()
.fromString(data.toString())
.subscribe(function (jsonObj) {
return new Promise(function (resolve, reject) {
filteredThing = new Notification(jsonObj);
filteredThing.save()
.then(result => {
console.log(result);
callback(result) **// THIS IS THE RESULT I NEED IN MY FRONT END**
})
.catch(err => {
console.log(err);
});
resolve();
});
});
});
}
})
When i go to localhost/notification i get:
ReferenceError: data is not defined
Thanks in advance!

Access Function in a Exported Module

I would like to create a module, where i have a function where i can insert a sql statement and get the result as recordset. Im new to nodeJs and have some trouble in accessing the functions right.
my Modul (sql.js)
var exports = module.exports = {};
sql = require('mssql');
let config = {
user: '###',
password '###'
server: '###',
database: '###',
driver: "###",
options: {
trustedConnection: true
}
};
var db = function (query) {
var rc;
console.log('verbinde');
sql.connect(config, function (err) {
console.log('verbinde');
if (err) console.log(err);
let request = new sql.request();
request.query(query, function (err, recordset) {
if (err) console.log(err);
console.log(recordset);
rc = recordset;
});
})
sql.close();
}
exports.db = db;
call
const ipc = require('electron').ipcMain;
const sql = require('../../customModules/sql.js');
console.log(sql.db('SELECT * FROM devices'));
i get an undefined.
it seems like, the sql.connect isnt rly called.
You might get better results using a Promise. Perhaps something like this (untested):
// sql.js
var db = (query) => new Promise((resolve, reject) => {
console.log('verbinde');
sql.connect(config, function (err) {
console.log('verbinde');
if (err) reject(err);
let request = new sql.request();
request.query(query, function (err, recordset) {
if (err) reject(err);
console.log('got those records!');
resolve(recordset);
});
})
sql.close();
})
// call
const ipc = require('electron').ipcMain;
const sql = require('../../customModules/sql.js');
sql.db('SELECT * FROM devices')
.then(data => console.log(data))
.catch(e => console.log(e));

Is there anything wrong with async/await in my code

Express API with mysql2
I want to use the async and await to query the data from the product table but nothing print at all, don't know how to use it properly.
exports.getAllTours = function(req, res) {
getTours()
.then(data => console.log(data))
.catch(err => console.log(err ));
}
async function getTours() {
var sql = "Select * from product_prd"
return new Promise(async function(resolve, reject) {
let [rows, fields] = await poolQuery(sql)
setTimeout(function() {
resolve(rows);
}, 500);
})
.catch(err => reject(err));
}
async function poolQuery(sql, args) {
return new Promise((resolve, reject) => {
promisePool.query(sql, args, (err, rows) => {
if (err)
return reject(err);
resolve(rows);
}).catch(err => reject(err));
});
}
I created the pool of connection like this by following the official documentation of mysql2
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'super',
port: '3307',
password: 'sohail',
database: '784413_wonder',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// now get a Promise wrapped instance of that pool
const promisePool = pool.promise();
module.exports = promisePool;
I'm pretty sure there is a SQL error, and you cannot figure it out because the error handling in getTours is wrong.
Try this:
exports.getAllTours = function(req, res) {
getTours()
.then(data => console.log(data))
.catch(err => console.log(err ));
}
async function getTours() {
var sql = "Select * from product_prd"
return new Promise(async function (resolve, reject) {
let rows;
let fields;
try {
[rows, fields] = await promisePool.query(sql, args);
} catch (err) {
reject(err);
}
setTimeout(function () {
resolve(rows);
}, 500);
});
}

Resources