This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
From my code, I want the value in _status variable after query and write file from MongoClient.connect, but I get NULL from return _status. How can I pass the value outside the function? Thank you for your answer.
function query(domain)
{
var _status;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("zone").find({"name" : domain}).toArray(function(err, result) {
if (!err) {
fs.writeFile('/root/'+domain+'.txt', result, function (err) {
if (err) throw err;
});
_status = "success";
}
else {
_status = "fail";
}
});
db.close();
});
return _status;
}
You are calling asynchronous functions( MongoClient.connect, .find) inside your function query, and trying to get the result(_status) synchronously. This does not work. You can use a callback based approach or a promise based approach to let the value of _status known to the caller.
Please refer here for more on promises.
try something like that
function query(domain, callback)
{
var _status;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("zone").find({"name" : domain}).toArray(function(err, result) {
if (!err) {
fs.writeFile('/root/'+domain+'.txt', result, function (err) {
if (err) throw err;
});
_status = "success";
}
else {
_status = "fail";
}
callback(_status);
});
db.close();
});
}
query(domain, (status) => {
// Synchronous
// do something
console.log(status);
});
Related
So this question might be a javascript concept question. but I cannot figure out why
I retrieve data from mongodb however, I cannot define _res variable to become the result.
console.log(_res) will return undefined.
Does anyone know why? and how to make it work as it should be?
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm").find(query).toArray( function(err, result) {
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData
db.close();
res.render('index.ejs', {
vmData: vmData
});
});
});
console.log(_res)
});
Mongodb query is an asynchronous operation. The console statement is executed before the query has been processed.
You define _res outside which is undefined outside, so the same value is consoled outside.
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm")
.find(query)
.toArray((err, result){
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData
db.close();
console.log('Inside', _res) // <---Should give you correct result
res.render('index.ejs', {
vmData: vmData
});
});
});
console.log('Outside', _res);
});
The code is being executed asynchronously due to which when the console.log is executed the _res is undefined.
Try to execute your logic when the asyn methods are being executed.
app.route('/').get(function(req,res){
let _res;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("vm");
var query = {};
dbo.collection("vm").find(query).toArray( function(err, result) {
if (err) throw err;
var vmData = JSON.stringify (result)
_res = vmData;
console.log(_res);
db.close();
res.render('index.ejs', {
vmData: vmData
});
});
});
});
getting undefined all the time "main.js":
var dbAccess = require('../dao/dbAccess');
dbaInstance = new dbAccess();
var wordPool = dbaInstance.getWordPool();
console.log (wordPool);
and "dbAccess.js" contains:
var DatabaseAccess = function() {}
DatabaseAccess.prototype.getWordPool = function () {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
//console.log(wordPoolFromDB); -working ok
return (wordPoolFromDB);
});
}
module.exports = DatabaseAccess;
why is it not working?
DatabaseAccess.prototype.getWordPool is not returning any result.
Since you are using an asynchronous function, you need do one of these things:
a) Take a callback as parameter and invoke the callback with a result
DatabaseAccess.prototype.getWordPool = function (cb) {
RoundWord.find({}, 'words decoys', function(err, results) {
if (err) {
return cb(err, null);
}
cb(null, results);
});
}
The callback convention is: cb(error, results...)
b) Use promises
DatabaseAccess.prototype.getWordPool = function () {
return RoundWord.find({}, 'words decoys', function (err, results) {
if (err) {
throw err; // however you might want to sanitize it
}
return results;
});
}
To consume this result you will need to do it as a promise
databaseAccess.getWordPool()
.catch(function (err) {
// process the error here
})
.then(function (results) {
// something with results
});
It will work if you change to this:
var dbAccess = require('../dao/dbAccess');
dbaInstance = new dbAccess();
dbaInstance.getWordPool(function(wordPool){console.log (wordPool);});
And:
var DatabaseAccess = function() {}
DatabaseAccess.prototype.getWordPool = function (cb) {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
//console.log(wordPoolFromDB); -working ok
cb(wordPoolFromDB);
});
}
module.exports = DatabaseAccess;
If the function is Asynchronous you need to pass a callback to find to get the result:
DatabaseAccess.prototype.getWordPool = function (callback) {
RoundWord.find({},'words decoys', function(err, wordPoolFromDB) {
if (err) throw err;
callback(err, wordPoolFromDB);
});
}
and call it as follows in main:
dbaInstance.getWordPool(function (err, wordPool) {
console.log (wordPool);
// wordPool is only available inside this scope,
//unless assigned to another external variable
});
// cannot access wordPool here
I'm using mssql(Microsoft SQL Server client for Node.js) package from npm.I'm trying to execute a stored procedure residing in my sql server database.Everything works fine.However what I want to do is return the recordsets so that i can export this to be used in other module.Below is what I'm trying to do.
function monthlyIceCreamSalesReport (scope){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return;
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
}
else {
console.log(recordsets[0]); // successfully receiving the value
}
connObj.conn.close();
});
});
console.log('check for recordsets', recordsets[0]); // undefined
return recordsets[0];
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
As shown in the code snippet, since the value of recordsets[0] is undefined, exporting this function is of no use.
You can't return this way in async nature. You can get it by passing the callback function
Try to give a callback function like this
function monthlyIceCreamSalesReport(scope, callback) { // pass a callback to get value
var connObj = connConfig();
connObj.conn.connect(function(err) {
if (err) {
console.log(err);
return;
}
connObj.req.input('Month', 4);
connObj.req.input('Year', 2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue) {
if (err) {
console.log(err);
} else {
console.log(recordsets[0]);
connObj.conn.close();
return callback(null, recordsets[0]); //return as a callback here and get that value in callback from where you called this function
}
});
});
}
var sqlServerObj = {
monICSalesReport: monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
Note: See the comment to understand the changes
recordsets[0] is undefinded, because is defined only in connObj.req.execute function scope. You may do this in this way:
function monthlyIceCreamSalesReport (scope, cb){
var connObj = connConfig();
connObj.conn.connect(function(err){
if(err){
console.log(err);
return cb(Error("Something wrong"));
}
connObj.req.input('Month',4);
connObj.req.input('Year',2016);
connObj.req.execute('<myStoredProcedure>', function(err, recordsets, returnValue){
if(err){
console.log(err);
connObj.conn.close();
return cb(Error("Something wrong"));
}
else {
console.log(recordsets[0]); // successfully receiving the value
connObj.conn.close();
return cb(recordsets[0]);
}
});
});
}
var sqlServerObj = {
monICSalesReport : monthlyIceCreamSalesReport,
};
module.exports = sqlServerObj;
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
music.playsong = function(vars){
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
console.log(error)
return;
}else {
console.log("Success")
return result
}
})
}
I am currently calling this function as
music.playsong(data)
However in this function I can not access the underlying callback and get the value from that. How do I get this music.playsong() to return the result of the callback without blocking execution?
You want use a async function as sync. So it's not possible. So you need to change your method to be async like this :
music.playsong = function(vars, cb){
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
console.log(error)
process.nextTick(() => {
cb(error)
})
}else {
console.log("Success")
process.nextTick(() => {
cb(null, result)
})
}
})
}
music.playsong = function(vars){
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
return callback("Error",{});
}else {
console.log("Success")
return callback(""success",result)
}
})
}
function callback(data){
//TODO
}
It looks like that youtube.search is an asynchronous action.
In this case, you should use Promise
e.g.
music.playsong = function(vars) {
return Promise(resolve, reject) {
//vars is an array with a Key named "song"
youTube.search(vars["song"], 2, function(error, result) {
if (error) {
return reject(err);
}
console.log("Success")
return resolve(result);
}
})
}
}
music.playsong('').then(function(result) {
// you will get result here
});
In Promise, you will have resolve and reject for handling async action.
when resolve got called, it will pass data to .then
when reject got caleed, it will pass err to .catch
I am new to node, and also JavaScript callbacks.
I am trying to check if an account exists in mongo and then 'save it' if it doesn't and return an error if it does.
I am currently trying to figure this out outside of my express app. This is what i have..
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
if(err) throw err;
var query = { name : "www.website.com"}
findOne(db, query, function (doc) {
if(doc) {
console.log('account exists');
} else {
console.log('good to go');
}
console.dir(doc);
});
});
var findOne = function (db, query, callback) {
db.collection('accounts').findOne(query, function (err, doc) {
if(err) throw err;
db.close();
callback();
});
}
with the console.dir(doc); above returning as undefined. How do I wait for the findOne to return before using the callback to console.log or save the account?
The reason you are getting undefined is because when you call your callback your are not passing it the doc. That line should look like callback(doc).
Here is an updated version of your code with a few suggestions:
MongoClient.connect('mongodb://localhost:27017/main', function (err, db) {
if(err) throw err;
var query = { name : "www.website.com"}
findOne(db, query, function (err, doc) {
if(err) {
// something went wrong
console.log(err);
return;
}
if(doc) {
console.log('account exists');
console.dir(doc);
} else {
console.log('good to go');
}
});
});
var findOne = function (db, query, callback) {
db.collection('accounts').findOne(query, function (err, doc) {
db.close();
if(err) {
// don't use throw when in async code
// the convention is to call your callback with the error
// as the first argument (notice that I added an argument
// to the definition of your callback above)
callback(err);
}
else {
// call your callback with no error and the data
callback(null, doc);
}
});
}