I am New To async/await coding in node js. I am trying to fetch data from mysql and then populate the result into an object. But i am not finding a way how to do it in controller.js file.
My source code similar to this.
My Router File
const express = require("express");
const controller = require("controller");
const router = express.Router();
router.route("/").get(controller.findAll);
My Controller File
const model = require("model");
exports.findAll = async (req, res) => {
const all = model.getAll((err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving data.",
});
}
return data;
});
const user = model1.getUser((err, data) => {
if (err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving user.",
});
}
return data;
});
// somefunctionality(all, user);
// res.send(result);
};
My Model file
const con = require("./db");
// constructor
const Customers= function (customer) {
this.id = customer.id;
this.first_name = customer.first_name;
this.last_name = customer.last_name;
this.email = customer.email;
};
Customers.getAll = () => {
const query = `SELECT * FROM doctors`;
sql.query(query, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("customers: ", res);
result(null, res);
};
user model same as customer
Thanks for your help
The first thing I would do is covert your Customers.getAll method to return a promise:
model file
Customers.getAll = () => {
const query = `SELECT * FROM doctors`;
return new Promise((res, rej) => {
sql.query(query, (err, data) => {
if (err) {
console.log("error: ", err);
rej(err);
return;
}
console.log("customers: ", res);
res(data);
})
};
(Note that you'll probably have to do something similar to the getAll method for your User model)
Now, in the controller, you can use try/catch to handle any errors.
*controller file
exports.findAll = async (req, res) => {
try {
const all = await model.getAll();
const users = await model1.getUser();
const result = somefunctionality(all, user);
res.send(result);
} catch(err) {
res.status(500).send({
message: err.message || "Some error occurred while retrieving data.",
});
}
};
Related
Cannot get the async / await functions to work properly in my card game app.
(a) I get the 201 response with no data.
(b) the deck document seems to be created afterwards, with the players field an empty array, indicating it is done after the deck is saved to the mongoDB
Below is my code. Any help is appreciated.
router.js
router.post('/game', (req, res, next) => {
try {
const { cards, playerNames, attributes } = req.body;
const newDeck = deck.start(cards, playerNames, attributes);
res.status(201).send(newDeck);
} catch (err) {
next(err);
};
});
/services/deck.js
exports.start = async (cards, playerNames, attributes) => {
try {
const users = await user.create(playerNames);
const deck = new Deck({
cards,
attributes,
players: users
});
return await deck.save((err, newDeck) => {
if (err) console.log(err);
console.log('RESULT', newDeck);
});
} catch (err) {
console.log(err);
}
};
/services/user.js
exports.create = async (users) => {
if (users.constructor === String) {
const user = new User({displayname: users});
return await user.save((err, newUser) => {
if (err) console.log(err);
console.log('NEW USERS ', user);
return newUser;
});
} else if (users.constructor === Array) {
let userList = [];
await users.forEach(name => {
const user = new User({displayname: name.toString()});
return user.save((err, newUser) => {
if (err) {
console.log(err);
} else {
userList.push(newUser);
return newUser;
}
});
});
console.log('NEW USERS ', userList);
return userList;
};
};
I am not familiar how you're handling promises,
but forEach is not promise-aware, that's how it has been designed, so it will not handle your asynchronous code properly
replace it with normal for loop or for-of loop, and add the await keyword in front of the user.save() method
I have my main routes file called main.js, in which I want to call sql functions from a module called database.js Within the database.js file I am able to retrieve the data, however when passing to main.js it keep saying that data is undefined.
main.js
const database = require('./modules/database')
app.get('/', async(req, res) => {
try {
const data = database.getAll()
console.log(data)
res.render('home', {stock: data})
} catch(err) {
console.log(err.message)
res.render('empty')
}
})
database.js
const sqlite3 = require('sqlite3').verbose()
const db = new sqlite3.Database('./stockInventory.db', (err) => {
if (err) return console.error(err.message)
console.log('Connected to the "stockInventory.db" SQlite database.')
})
module.exports.getAll = () => {
const sql = 'SELECT * FROM stock;'
console.log(sql)
db.all(sql, (err, data) => {
if(err) console.error(err.message)
//console.log(data)
return data
})
}
You need callback function, Try this
const database = require('./modules/database')
app.get('/', async(req, res) => {
try {
database.getAll(function(data) {
console.log(data)
res.render('home', {stock: data})
})
} catch(err) {
console.log(err.message)
res.render('empty')
}
})
module.exports.getAll = (callback) => {
const sql = 'SELECT * FROM stock;'
console.log(sql)
db.all(sql, (err, data) => {
if(err) console.error(err.message)
//console.log(data)
callback(data);
})
}
I new in Nodejs and faced some problems and need help
I broke down my app into modules and controllers
in app.js
app.use('/api/sync', syncDataRouter)
and in syncDataRouter.js
const routes = function (con, Reading, ReadingSummary) {
const syncDataRouter = express.Router();
const syncDataController = require('../controller/syncDataController')(con, Reading, ReadingSummary);
//Get All Readings from Database and push it to Mongo-db
syncDataRouter.route('/')
.get(syncDataController.sync);
return syncDataRouter;
};
module.exports = routes;
and in controller
const syncDataController = function (con, Reading, ReadingSummary) {
function getAllCompletedSessions() {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM session WHERE endTime IS NOT NULL';
con.query(sql, (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
function getSessionPlayers(sessionId) {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM sessionplayers WHERE sessionId = ?';
con.query(sql, [sessionId], (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
const sync = (req, res) => {
getAllCompletedSessions()
.then(sessions => {
})
.catch(err => {
res.status(500).send({ message: err.message });
});
//The Problem
res.json('Done');
};
return {
sync: sync
}
}
module.exports = syncDataController;
the problem is if any error happened enter a catch block and also continue until res.json('Done'); and sent a message can't set headers after they are sent how to handle a situation like that
Try making the sql queries async
const syncDataController = function (con, Reading, ReadingSummary) {
async function getAllCompletedSessions() {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM session WHERE endTime IS NOT NULL';
await con.query(sql, (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
async function getSessionPlayers(sessionId) {
return new Promise((resolve, reject) => {
const sql = 'SELECT * FROM sessionplayers WHERE sessionId = ?';
await con.query(sql, [sessionId], (err, rows) => {
if (err) reject(new Error(err));
resolve(rows);
});
});
};
const sync = (req, res) => {
getAllCompletedSessions()
.then(sessions => {
})
.catch(err => {
res.status(500).send({ message: err.message });
});
//The Problem
res.json('Done');
};
return {
sync: sync
}
}
module.exports = syncDataController;
I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;
I have declare the variable first. but if I do console.log(userinsertData) outside looping variable still not fill.
what i should do for solving this problem?
here my code:
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
try {
data.forEach(function(item, index) {
var userdata = new User();
userdata.name = item.name;
userdata.age = item.age;
userdata.sex = item.sex;
userdata.save(function(err, data) {
if (err) {
res.send(err)
} else {
userinsertData.push(data);
}
});
})
} catch (e) {
res.json({
message: 'data not valid'
})
}
console.log(userinsertData);
res.json({
message: 'musician created!',
data: userinsertData
});
}
};
you should solve the problem as
async.eachSeries(data, function (info, callback) {
//here process your data and call callback() for next iteration
}, function (err) {
if (err) {
//this will be called after all iterations and in case of error
}else{
console.log('Well done :-!');
//this will be called after all interations successfully
}
});
this problem you are facing is because of asynchronous nature of nodejs and async helps you to introduce blocking.
Don't forget to include async
Use promise
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
new Promise(function(resolve, reject) {
data.forEach(function(item, index) {
var userData = new User(item);
userData.save(function(err, data) {
// if error, reject
if(err) return reject(err);
// we have proceed all items in data, resolve it
else if(data.length - 1 === index) return resolve(userinsertData);
// not finished yet, keep proceeding
else userinsertData.push(data);
});
}).then(function(successResult) {
res.json({
message: 'musician created!',
data: successResult
});
}, function(errorResult) {
res.json({
message: 'data not valid'
});
});
}
};
Use callbacks
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
function saveUser(callback) {
data.forEach(function(item, index) {
var userData = new User(item);
userData.save(function(err, data) {
// if error, return callback with error
if(err) return callback(err);
// we have proceed all items in data, return data
else if(data.length - 1 === index) callback(null, userinsertData);
// not finished yet, keep proceeding
else userinsertData.push(data);
});
}
saveUser(function(err, users) {
if(err) return res.json({message: 'data not valid'});
res.json({
message: 'musician created!',
data: users
});
});
}
};
This is what async package does internally