This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
function emailExist(e) {
const sqlstmt = "SELECT email FROM somewhere WHERE email = ? LIMIT 1";
db.query(sqlstmt, [e], (err, result) => {
//supposed to return 0 or 1
return result.length
});
}
console.log(emailExist('someone#gmail.com')); //returns undefined
I tried using variables, still returned undefined
The problem is that you are trying to return a value from the callback.
To get the value from the callback, which will be called after a certain period of time. There are several ways to solve this problem, for example, you can wrap your callback in a Promise:
function query(sqlstmt) {
return new Promise((resolve, reject) => {
db.query(sqlstmt, [e], (err, result) => {
if(err) {
return reject(err);
}
resolve(result.length);
});
})
}
async function emailExist(e) {
const sqlstmt = "SELECT email FROM somewhere WHERE email = ? LIMIT 1";
const result = await query(sqlstmt);
return result;
}
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return results of node's sqlite3 in a function?
(1 answer)
Closed 9 months ago.
function getAllUsers1 (){
var con = new sql.connect(config,(err)=>{
if(err){
console.log(err)
return err ;
}else{
console.log('1');
con.query("select * from WebMail_Send", function (err,data){
if(err){
console.log('invaled query..............');
return err ;
}else{
console.log(data);
return data;
}
})
}
});
}
router.get('/sql',(req,res,next)=>{
var getAllUsers = new getAllUsers1();
res.render('sql', { items: getAllUsers})
});
No Error but return nothing
I'm trying to get data from SQL DB and display it on the HBS page.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Hello could someone inform me how do I return the value of a query to use in another class This is my query:
var pconn = require('./db.js');
var dadosMsg = null
function getValueMsg(){
pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM bor_msg b LIMIT 1', (err, rows) => {
if (!err) {
dadosMsg = rows.rows[0];
return dadosMsg;
} else {
return err;
console.log(err);
}
});
}
I would like to return the query value in this class
var x = require('./dbmsg');
x.getValueMsg();
console.log(x.dadosMsg.valor_msg);
You can use Promise.
A Promises are used to handle asynchronous operations in JavaScript
Promise constructor takes only one argument,a callback function.
Callback function takes two arguments, resolve and reject
Perform operations inside the callback function and if everything went well then call resolve.
If desired operations do not go well then call reject.
function getValueMsg() {
return new Promise((resolve, reject) => {
pconn.pool.query('SELECT b.numero_serie, b.grupo_msg, b.index_msg, b.valor_msg FROM bor_msg b LIMIT 1', (err, rows) => {
if (!err) {
dadosMsg = rows.rows[0];
resolve(dadosMsg);
} else {
console.log(err);
reject(err);
}
});
});
}
// other file
var x = require('./dbmsg');
//You can consume Promises using then and .catch methods.
x.getValueMsg().then((results)=>{
console.log(results);
}).catch((err)=>{
console.log(err);
})
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Below is my JS Method
function test(key, language) {
var uri = '/Resources/ValidationMessages.json';
fetch(uri).then(response => {
return response.json();
}).then(data => {
console.log('Inside Function - ' + data[key]);
return data[key];
}).catch(err => {
console.log(' Error ');
});
}
And after calling this method as
var v = test('spnrequiredRegisterEmail');
console.log('Outside Function - ' + v);
Inside the function it print value but Outside Function statement is always undefined.
The solution that I am trying to achieve is that I have to set some text in n number of span as inner text, which will come through this function call after passing the respective key, but every span displays undefined as inner text
It won't wait for a method to finish , so how can I solve this issue?
Try using async / await
async function test(key, language) {
try {
var uri = '/Resources/ValidationMessages.json';
var resp = await fetch(uri);
var data = resp.json();
console.log('Inside Function - ' + data[key]);
return data[key];
catch(err) {
console.log(err);
}
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to make a function wait until a callback has been called using node.js
(11 answers)
Closed 5 years ago.
I'm learning node.js and I have a problem. How to get data from function to variable?
function loadOrInitializeTaskArray(file, cb) {
fs.exists(file, function(exists) {
var tasks = [];
if (exists) {
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
var data = data.toString();
var tasks = JSON.parse(data || '[]');
cb(tasks);
})
} else {
cb([]);
}
})
}
function listTasks(file) {
loadOrInitializeTaskArray(file, function(tasks) {
for (var i in tasks) {
console.log(tasks[i]);
}
})
}
Function listTasks works correctly, but I would like create own function, for example customListTasks:
function customListTasks(file) {
var list = loadOrInitializeTaskArray(file, function(){});
console.log(list);
}
This not return me errors, but console.log on list return me "undefined". How can I get this data to variable list?
Short answer: you can not.
Because the loading in loadOrInitializeTaskArray is asynchronous, all the magic has to happen in the callback that you are passing. You cannot just 'return' a value from it.
Option 1: Place all logic that depends on the loaded data in the anonymous function that you pass as callback.
var list = loadOrInitializeTaskArray(file, function(tasks){
console.log(tasks);
});
Option 2: Use Promises. They work essentially like callbacks, but are slightly more flexible and make chaining easier.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Heres my code. I basicly want to return the 'body' var in my getFollows function. Setting vars obviously dont work, no idea how to get the variable. I can't change getUserFollowedChannels because its a package, and I need to return it to the function directly because of meteor server->client stuff.
'twitch.getFollows'() {
var followers = twitch.getUserFollowedChannels('atlatonin', function(err, body) {
if (err) {
return err;
} else {
console.log(body.follows[0].channel.display_name);
return body.follows[0].channel.display_name;
}
});
return followers;
},
You can pass a callback function as below:
'twitch.getFollows': function(done) {
twitch.getUserFollowedChannels('atlatonin', done);
}
And invoke the function as below:
twitch.getFollows(function(err, body) {
if (err) {
console.log(err);
//return err;
} else {
console.log(body.follows[0].channel.display_name);
//return body.follows[0].channel.display_name;
}
});