This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I'm new to node and promises. I have two files - server.js and db.js
server.js imports db.js as modules.
I'm fetching some data from a SQL database in a db.js module and I'm trying to pass that data to a function in server.js.
I've successfully fetched the data from database, but when I try to pass it to the function in server.js, it only returns an undefined value.
Here's the code
server.js
const db = require('./db.js');
app.post('/api/trigger-push-msg/', function (req, res) {
return getSubscriptionsFromDatabase()
.then(function(subscriptions) {
// Do something
});
});
function getSubscriptionsFromDatabase() {
return new Promise((resolve, reject) => {
let subscriptions = db.getSubscriptions();
console.log(subscriptions); // this only prints "undefined"
if (subscriptions != undefined) {
resolve(subscriptions);
} else {
reject("No"); // this executes
}
})
}
db.js
module.exports = {
getSubscriptions: function() {
var sql = "SELECT * FROM subscriptions";
con.query(sql, function(err, result) {
if (err) throw err;
console.log(result); // this prints the same result as I want
return result;
})
}
}
getSubscriptions doesn't have a return statement
and considering that there's some async content in it you should wrap all inside a promise and trigger the subsequent logic only after it resolves.
module.exports = {
getSubscriptions: function() {
var sql = "SELECT * FROM subscriptions";
return new Promise(function(resolve, reject){
con.query(sql, function(err, result) {
if (err) return reject(err);
resolve(result);
})
})
}
}
then:
function getSubscriptionsFromDatabase() {
return db.getSubscriptions()
.then(function(subscriptions){
return subscriptions;
})
}
and in your route:
app.post('/api/trigger-push-msg/', function (req, res) {
getSubscriptionsFromDatabase()
.then(function(subscriptions) {
res.send(subscriptions);
})
.catch(function(err){
res.sendStatus(500);
})
});
Related
Please help me, I need to implement a function in a separate module file and in the route where the render has to call this function receiving the query data:
function getSobre() {
return new Promise((resolve, reject) => {
db.query(`SELECT * FROM sobre ORDER BY cod DESC LIMIT 1`, (err, results) => {
if (err) {
return reject(err);
} else {
return resolve(results);
}
});
});
}
const data = {
title: getSobre().then(data => {
/*
* HERE How do I return this "data" to the "title:" ?????????????
*/
}),
name: 'Fabio',
profession: 'Analista'
}
module.exports = data;
db.query is a Js callback . Which will wait for the result , then return anything.
So data will always be empty since it is getting returned much before db.query getting full resolved
You should wrap this in a native promise, and then resolve the promise :
function getTabela{
return new Promise(function(resolve, reject) {
// The Promise constructor should catch any errors thrown on
// this tick. Alternately, try/catch and reject(err) on catch.
let sql = "SELECT * FROM sobre ORDER BY cod DESC LIMIT 1";
var data = {};
db.query(sql, (err, results, fields) => {
if (results.length > 0) {
resolve(fields)
} else {
console.log('Erro: ' + err);
}
});
});
}
getTabela().then(function(rows) {
// now you have your rows, you can see if there are <20 of them
}).catch((err) => setImmediate(() => { throw err; }));
This way you should always have the data which is expected out of the query.
I have my function who call the DB to do something :
function callQuery(query) {
db.query(query, (err, res) => {
if (err) {
// Error DB connecion
console.log(err.stack)
} else {
// Send back the results
return(res.rows[0])
}
})
}
My problem is when I call this function by :
const idUser = callQuery("INSERT INTO blablabla RETURNING *")
My data is successfully added in the DB, but idUser came null. It should be res.rows[0]
I am using this tutorial (who instead of setting a variable, call console.log) : https://node-postgres.com/features/connecting
Thank you in advance
I think this is something due to asynchronous
let promisess = new Promise(function(resolve, reject) {
function callQuery(query) {
db.query(query, (err, res) => {
if (err) {
// Error DB connecion
console.log(err.stack)
} else {
// Send back the results
resolve(res.rows[0])
}
})
}
});
promisess.then((res)=> {
your data in res
});
I do not know what should be the problem but I currently implemented function that convert csv file to JSON and print result into console.log
function looks like :
var Converter = require("csvtojson").Converter;
var converter = new Converter({delimiter: ';'});
function convertToJSON() {
converter.fromFile('data.csv', function(err, result) {
if (err) {
console.log(err);
}
var data = result;
console.log(result);
});
}
and when I call it this way in server.js it return JSON to console
convertToJSON();
but when I would like to call this function from app.get by REST GET it return allways empty object.
app.get("convertToJSON", function(req,res){
convertToJSON();
})
I dont know what should be problem, why it is not work inside get call. There is no error during execution.
Your code has become asynchronous use a promise in that funtion.
Your file is taking more time to load when called inside app.get.
function convertToJSON() {
var promise1 = new Promise(function(resolve, reject) {
converter.fromFile('data.csv', function(err, result) {
if (err) {
reject(err);
}
var data = result;
resolve(result);
});
});
return promise1;
}
As we're using Promise, we need to handle it properly. Please take a look at this reference for more details.
Try this...
var Converter = require("csvtojson").Converter;
var converterObj = new Converter({delimiter: ';'});
function convertToJSON() {
return new Promise((resolve, reject) => {
converterObj.fromFile('data.csv', (err, result) => {
if (err) {
reject(err);
}
resolve(result);
});
});
}
convertToJSON()
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log(error);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I want to assign data return from the model, then on console.log i only see
undefined
My code is:
var dmodel = require('../models/database');
dmodel.myfunction(request,response, function (err, user) {
console.log(user); // see data
});
Then I repair code:
var dmodel = require('../models/database');
var userinfo;
dmodel.myfunction(request,response, function (err, user) {
userinfo = user;
});
console.log(userinfo); // undefined, not see data
How do it ? Thanks all
This is my function:
module.exports = {
myfunction: function (request,response, callback) {
var query = "select * from mytable";
//call functionexcecute query
executeQuery(query, function (err, rows) {
if (!err) {
var user = rows;
callback(null, user);
} else {
console.log(err);
}
});
}
};
Due to asynchronous nature of javascript, code console.log(userinfo) is getting executed before the callback function is called.
Modified code:
var dmodel = require('../models/database');
var userinfo;
dmodel.myfunction(request,response, function (err, user) {
userinfo = user;
console.log(userinfo);
});
That is, your earlier code was correct. If the value printed is still undefined, that means there is some issue with the definition of function executeQuery.
you can use a .then promise which will wait for the first function to complete its execution
var dmodel = require('../models/database');
var userinfo= {};
dmodel.myfunction(request,response, function (err, user) {
userinfo = user;
return userinfo;
}).then(function(data){
console.log(userinfo);
})
I am trying to do a nested query with MySql, put the result inside a variable and send over http, but the program always run console.log("test 2:"+rpsData); before the query finish. I already tried this, but still getting the same problem.
const express = require('express')
const app = express()
const mysql = require('mysql');
const Connection = require('mysql/lib/Connection');
const Promise = require('bluebird');
Promise.promisifyAll([
Connection
]);
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root123',
database : 'mygallery'
});
app.get('/posts', function(request, response) {
var rpsData;
connection.connectAsync()
.then(function() {
connection.query('SELECT * FROM post WHERE approved = 1', function(err, rows, fields) {
if (err) throw err;
rpsData = rows;
for (var i in rows) {
connection.query('SELECT * FROM image WHERE postCode = ?', [rpsData[i].postCode], function(err, rows, fields) {
if (err) throw err;
rpsData[i].image = rows;
console.log("test 1:"+rpsData);
});
}
});
})
.then(function() {
response.send(rpsData);
console.log("test 2:"+rpsData);
})
.catch(function(error) {
console.error('Connection error.', error);
});
});
What's happening here is you're not tying all of the pieces of async code to the promise chain. Once we convert it to do so this should work.
First lets wrap calls to connection.query to return a promise. We then have to return that generated promise to attach it to the outer promises chain.
If you don't return a promise, it won't know that it has to wait for your code to finish executing and will move forward with the next .then() statement on the outside promise (from connection.connectAsync);
You need to apply the same treatment to the inner query.
Sample code:
app.get('/posts', function(request, response) {
connection.connectAsync()
.then(function() {
return new Promise(function(resolve, reject) {
connection.query('SELECT * FROM post WHERE approved = 1', function(err, rows, fields) {
if (err) reject(err);
resolve(rows.reduce(function(accumulator, current) {
return accumulator.then(function(rpsData){
return new Promise(function(resolve, reject){
connection.query('SELECT * FROM image WHERE postCode = ?', [current.postCode], function(err, rows, fields) {
if (err) reject(err);
current.image = rows;
console.log("test 1:"+rpsData);
resolve(rpsData);
});
});
});
}, Promise.resolve(rows)));
});
});
})
.then(function(rpsData) {
response.send(rpsData);
console.log("test 2:"+rpsData);
})
.catch(function(error) {
console.error('Connection error.', error);
});
});
I'm queueing the internal promises using the technique I describe here