I'm learning node.js right now and I'm having troubles calling back.
I looked at Event Emitter but it doesn't seems to be relevant for me.
This is what I'm calling:
exports.search = function(lat, lng, Arr, callback) {
//something
geocoder.reverse({
lat: lat,
lon: lng
}, function(err, res, callback) {
//finding the area
if (area !== "null") {
pool.getConnection(function(err, connection, callback) {
if (err) {
} else {
connection.query("SOME SQL CODE", function(err, rows, fields, callback) {
if (found what Im looking
for) {
connection.query("SOME SQL CODE", function(err, rows, fields, callback) { //looking for something else
if (err) {
callback(true);
} else {
if (rows[0] === undefined) {
callback(true);
} else {
console.log("found!");
callback(null, rows[0]);
}
}
});
} else if (err) {
}
});
}
});
} else {
}
});
};
I'm getting my "found!" in the console log, but the callback doesn't working for some reason.
If I put a callback at the end of the function " search " it does call back, do I know I'm not having a problem with the function who gets the callback.
Thank you!
I think the callback(null, rows[0]) is call back of function geocoder.reverse. You can change name callback of search function is callback1 and then call as below.
exports.search = function(lat, lng, Arr, callback1) {
//something
geocoder.reverse({
lat: lat,
lon: lng
}, function(err, res, callback) {
//finding the area
if (area !== "null") {
pool.getConnection(function(err, connection, callback) {
if (err) {
} else {
connection.query("SOME SQL CODE", function(err, rows, fields, callback) {
if (found what Im looking
for) {
connection.query("SOME SQL CODE", function(err, rows, fields, callback) { //looking for something else
if (err) {
callback(true);
} else {
if (rows[0] === undefined) {
callback(true);
} else {
console.log("found!");
callback1(null, rows[0]);
}
}
});
} else if (err) {
}
});
}
});
} else {
}
});
};
You can apply async lib to your code so that your code is clear too.
It's better to use a library that helps you: like async or q
Related
the below function is generating the "x" is not a function error, for the love of me I have no idea why this is happening? any help is much appreciated.
function updateShareholder() {
var date = moment().format('MM/DD/YYYY');
console.log('updateShareholder');
var data = {
companyID: agreement.applicant.applicantCompanyID,
userID: agreement.coSigner.coSignerID,
agreementID: agreement.agreement.agreementID,
stock: agreement.stock.stock
}
company_worker.updateShareholder(data, function(err, result) {
if (err) {
console.log(err);
res.send(err);
} else {
console.log('updateShareholder');
process.nextTick(function() {
emailNotification()
});
}
});
};
if it helps here is the company worker function that is called within.
module.exports.updateShareHolder = function(req, callback) {
console.log('updateShareHolder');
Company.update({
"_id": req.companyID,
"shareHolders.userId": req.userID
}, {
$push: {
"shareHolders.$.agreements": {
agreementID: req.agreementID
}
}
}, {
$set: {
"shareHolders.$.shares": ++req.shares
}
},
function(err) {
if (err) {
console.log(err);
callback(err, err);
} else {
console.log('updateShareHolder');
callback(null, 'success');
}
})
};
and this is the function that calls the so-called broken function
function moveOn() {
if (addShareHolder == 'true') {
process.nextTick(function() {
addShareholder()
});
} else if (updateShareholder == 'true') {
process.nextTick(function() {
updateTheShareholder()
});
}
};
There's a typo in the function name.
You are exporting module.exports.updateShareHolder and calling company_worker.updateShareholder. Notice the lowercase h,
I have an async waterfall Array where the function otherIngrLists() is the 3rd to be executed. Every function before that worked fine.
function otherIngrLists(userslist, callback){
collection = db.get('ingrList');
collection.find({"userid":{$ne:userid}},{},function(err,docs){
if(!err){
var otherLists = docs;
var otherListsCount = docs.count();
console.log(otherListsCount);
callback(null, otherLists, otherListsCount, userslist);
} else {
callback(err, null);
}
});
},
The Problem is that this function is called twice. I assured this with a simple console.log().
How did I manage to call this function again? Did I get the concept of callbacks wrong as I use them to be passed on to the next function?
Also after this function executing twice an error ist thrown. It has nothing to to with this problem though and I will concern my self with that later.
Thank you for your time!
Waterfall Array in router.get:
router.get('/:userid', function(req, res) {
var db = req.db;
var collection;
var userid = req.params.userid;
async.waterfall(
[
function getIngrList(callback, userid) {
var route = 'http://localhost:3000/users/zutatenliste/'+userid;
request(route, function(err, response, body){
if (!err && response.statusCode === 200) {
var userlist = body;
callback(null, userlist);
} else {
callback(err, null);
return;
}
});
},
function otherIngrLists(userlist, callback){
collection = db.get('zutatenListe');
console.log(userid);
collection.find({"userid":{$ne:userid}},{},function(err,docs){
if(!err){
var otherLists = docs;
var otherListsCount = docs.count();
callback(null, otherLists, otherListsCount, userlist);
} else {
callback(err, null);
}
});
},
function pushInArray(otherLists, otherListsCount, userlist, callback){
console.log("test");
...
...}
}
}
Edit 1: --Also either if cases are executed, first the true one then the false--
// Does not happen anymore
Edit 2: Added the whole Thing until the problematic function
Please provide some Additional details as this function seems perfect and No, You haven't misunderstood the concept of callback you are using it correctly.
Structure of Async Waterfall
var create = function (req, res) {
async.waterfall([
_function1(req),
_function2,
_function3
], function (error, success) {
if (error) { alert('Something is wrong!'); }
return alert('Done!');
});
};
function _function1 (req) {
return function (callback) {
var something = req.body;
callback (null, something);
}
}
function _function2 (something, callback) {
return function (callback) {
var somethingelse = function () { // do something here };
callback (err, somethingelse);
}
}
function _function3 (something, callback) {
return function (callback) {
var somethingmore = function () { // do something here };
callback (err, somethingmore);
}
}
so, in waterfall you can pass the values to the next function and your 3rd function is correct.
Edited
async.waterfall(
[
//can not give userId as second parameter
function getIngrList(callback) {
//if you want userId you can pass as I shown above or directly use here if it's accessible
var route = 'http://localhost:3000/users/zutatenliste/'+userid;
request(route, function(err, response, body){
if (!err && response.statusCode === 200) {
var userlist = body;
callback(null, userlist);
} else {
callback(err, null);
// return; no need
}
});
},
function otherIngrLists(userlist, callback){
collection = db.get('zutatenListe');
console.log(userid);
collection.find({"userid":{$ne:userid}},{},function(err,docs){
if(!err){
var otherLists = docs;
var otherListsCount = docs.count();
callback(null, otherLists, otherListsCount, userlist);
} else {
callback(err, null);
}
});
},
function pushInArray(otherLists, otherListsCount, userlist, callback){
console.log("test");
...
...}
As said you can not pass userId as last parameter over there. Let me know if you still get the same error.
First you need to declare you function:
function myFuntion(userId, callback) {
async.waterfall([
function(callback) {
//do some thing here
callback(null, userlist);
}, function(userId, callback) {
//do something here
callback(null, orderList, orderListCount, userlist);
}
], function(err, orderList, orderListCount, userlist) {
if(err)
console.log(err);
else
callback(orderList, orderList, userlist);
})
}
After that you can use function:
myFuntion(userId, function(orderList, orderListCount, userlist) {
console.log(orderList);
console.log(orderListCount);
console.log(userlist);
})
Okay, so heres the full source of my function. All I want that the part that is surrounded by "////////////" would repeat. New function works too. I could have them both, very confused once I tried to pull the highlighted function into a new one and got loads of errors.
function reWebLogOn(steam, callback) {
steam.webLogOn(function(newCookie){
helper.msg('webLogOn ok');
cookies = newCookie;
offers.setup({
sessionID: currentSessionId,
webCookie: newCookie
}, function(){
if (typeof callback == "function") {
callback();
}
});
var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
{
steamid: config.steamid,
identity_secret: config.identitySecret,
device_id: device_id,
webCookie: newCookie,
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations)
{
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.FetchConfirmations received ' + confirmations.length + ' confirmations');
if ( ! confirmations.length)
{
return;
}
steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
{
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.AcceptConfirmation result: ' + result);
}).bind(this));
}).bind(this));
///////////////////////////////////////////////////////////////////////////////////////////////////////////
});
}
use timer's, an Interval would be handy
setInterval(function() {
//.. part that should be repleated
}, 30*1000);
window.setInterval() is your friend.
it executes a function at the provided interval of time.
for example, setInterval(()=>console.log("foo"),100) will log "foo" in the console every 100ms.
function reWebLogOn(steam, callback) {
steam.webLogOn(function(newCookie){
helper.msg('webLogOn ok');
cookies = newCookie;
offers.setup({
sessionID: currentSessionId,
webCookie: newCookie
}, function(){
if (typeof callback == "function") {
callback();
}
});
var steamcommunityMobileConfirmations = new SteamcommunityMobileConfirmations(
{
steamid: config.steamid,
identity_secret: config.identitySecret,
device_id: device_id,
webCookie: newCookie,
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////
setInterval((function(){
steamcommunityMobileConfirmations.FetchConfirmations((function (err, confirmations){
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.FetchConfirmations received ' + confirmations.length + ' confirmations');
if ( ! confirmations.length)
{
return;
}
steamcommunityMobileConfirmations.AcceptConfirmation(confirmations[0], (function (err, result)
{
if (err)
{
console.log(err);
return;
}
console.log('steamcommunityMobileConfirmations.AcceptConfirmation result: ' + result);
}).bind(this));
}).bind(this));
}).bind(this),30000)
Put your code inside setInterval(function(){},1000) timer or do some recursive calls.
function(dataValue, cb) {
req.app.db.models.User.find({
_id: { $ne: dataValue._id }
}, function(err, totalUser) {
if (!err) {
var len = totalUser.length;
if (len !== 0) {
req.app.utility.async.map(totalUser, function(each, callback) {
console.log(each);
req.app.utility.async.mapSeries(each.nonregisterContact, function(element, callback1) {
console.log('element', element.number);
console.log('dataValue', dataValue.mobileNumber);
console.log('kolka', Number(element.number) === Number(dataValue.mobileNumber));
if (Number(element.number) === Number(dataValue.mobileNumber)) {
each.registerContact.push(dataValue._id.toString());
each.nonregisterContact.splice(element, 1);
each.save(function(err, finalResult) {
if (!err) {
} else {
console.log(err);
}
})
callback1(null, null);
} else {
callback1(null, null);
}
}, function(err, final) {
if (!err) {
callback(null, null);
} else {
console.log(err);
}
});
}, function(err, result) {
if (!err) {
console.log('2');
return cb(null, dataValue);
} else {
console.log(err);
}
});
} else {
return cb(null, dataValue);
}
} else {
cb(err);
}
})
}
I don't get any response after each.save method call in the mapSeries method final callback.I am trying this solution.How i will do the same thing. How I resolve that and handle this kind of situation?
I tried to simplify code, but I'm not sure that my code realizes your needs. Also I cann't test it :D
dataValue, each, element, finalResult are very common names, so you should use them with caution to keep code is readable/supportable.
// very bad idea is include other libraries to app
var async = require('async');
var db = require('db'); // this module must export connection to db
...
function (dataValue, cb) {
// processUser use data from closure of current function => inside of current
function processUser (user, callback) {
async.mapSeries(user.nonregisterContact, function(contact, callback){
// Check and exit if condition is not satisfied. It's more readable.
if (Number(contact.number) !== Number(dataValue.mobileNumber))
return callback(null); // ignore user
user.registerContact.push(dataValue._id.toString());
user.nonregisterContact.splice(contact, 1);
user.save(function(err, finalResult) { // Is finalResult ignore?
if (err)
console.log(err);
callback(); // ingnore error
})
}, callback);
db.models.User.find({_id: { $ne: dataValue._id }}, function(err, userList) {
if (!err)
return cb(err);
if (userList.length == 0)
return cb(new Error('Users not found'));
// use named function to avoid stairs of {}
async.map(userList, processUser, cb);
})
};
I am new to Node.js and mongoose, i am trying to query objects from a mongo collection using find({}) and the function is as follows :
schema.statics.listAllQuizes = function listAllQuizes(){
Model.find({},function(err,quizes,cb){
if(err){
return cb(err);
}else if(!quizes){
return cb();
}
else {
return cb(err,quizes);
}
});};
But when i call this function i get an error saying
return cb(err,quizes);
^
TypeError: cb is not a function
I am stuck at this point, can someone please help me with this, thanks in advance.
The callback should an argument to listAllQuizes, not an argument to the anonymous handler function.
In other words:
schema.statics.listAllQuizes = function listAllQuizes(cb) {
Model.find({}, function(err, quizes) {
if (err) {
return cb(err);
} else if (! quizes) {
return cb();
} else {
return cb(err, quizes);
}
});
};
Which, logically, is almost the same as this:
schema.statics.listAllQuizes = function listAllQuizes(cb) {
Model.find({}, cb);
};
Here's an example on how to use it:
var quiz = App.model('quiz');
function home(req, res) {
quiz.listAllQuizes(function(err, quizes) {
if (err) return res.sendStatus(500);
for (var i = 0; i < quizes.length; i++) {
console.log(quizes[i].quizName)
}
res.render('quiz', { quizList : quizes });
});
}
Assuming you have code somewhere that looks like this:
foo.listAllQuizzes(function (err, quizzes) {
...
});
Then your function listAllQuizzes is passed a callback:
schema.statics.listAllQuizzes = function (cb) {
Model.find({}, function(err, quizzes) {
if (err) return cb(err);
cb(null, quizzes);
});
};