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);
})
Related
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;
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm trying to use a promise in my function but it never returns. This is my code:
function getData(id) {
return new Promise(function(resolve, reject) {
DbUtil.connection.query("my query... ", [id],
function (error, results, fields) {
if (error) {
reject(error);
} else {
resolve(results);
}
}
);
})
}
The query works and I can see its results in the else block. But the function itself doesn't return. I tried adding a return statement after the resolve, and also after the Promise function itself. But it still doesn't return.
What am I missing?
EDIT: how do I know the function doesn't return? Because
function main() {
var data = getData(1);
console.log("data returned? " + data);
}
in the above main function the log statement is never called.
It's not the proper way to handle a promise
Try this:
var data;
getData(1).then(function(d) {
console.log(d);
data = d;
});
// Since a Promise is async, you can't log data here
or
async function main() {
var data = await getData(1);
console.log(data);
}
Note that this examples does not handle catch case.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
Although I found similar questions to mine, I couldn't solve the problem on my own.
In my '../models/user' model I want to find all users and put them into array, and return that array to the controller(where I will use the info).
Here is my code:
var mongoDatabase = require('../db');
var database = mongoDatabase.getDb();
function find() {
var test;
database.collection("customers").find().toArray( function(err, docs) {
if(err) throw err;
console.log(docs); //works fine
//I'd like to return docs array to the caller
test = docs;
});
console.log(test); //test is undefined
}
module.exports = {
find
};
I also noticed, that 'console.log(test)' goes before 'console.log(docs)'. I tried passing 'docs' argument as function parameter to 'find', but without result.
The best way is to use Promises. Do it like this.
function getUsers () {
return new Promise(function(resolve, reject) {
database.collection("customers").find().toArray( function(err, docs) {
if (err) {
// Reject the Promise with an error
return reject(err)
}
// Resolve (or fulfill) the promise with data
return resolve(docs)
})
})
}
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.
How can I return the value of reverseGeocodeData using a promise (using the resolve method in the promise)?
geocoder.reverseGeocode(33.7489, -84.3789,function (err, reverseGeocodeData){
//something;
},
// Reverse Geocoding
return new Promise(function(resolve,reject){
resolve();
});
You have to resolve or reject the promise in the callback of the goecoder...
return new Promise(function(resolve, reject) {
geocoder.reverseGeocode(33.7489, -84.3789, function (err, reverseGeocodeData) {
if(err) return reject(err);
resolve(reverseGeocodeData);
});
});
This would be the basic implementation of a Promise. Depending on the promise library you're using there are of course other options. I prefer bluebird or when
this is an example using bluebird.js (http://bluebirdjs.com/docs/api/promise.promisify.html)
var Promise = require('bluebird');
var reverseGeocodePromise = Promise.promisify(geocoder.reverseGeocode);
reverseGeocodePromise(33.7489, -84.3789)
.then(function(result) {
// do something;
})
.catch(function(err) {
// handle error
})