Please bear with me on this. I can't seem to get my head round how I will be able to update the variable outside the FindOne function.
So:
var userPostCount;
userPostsModel.findOne({'profileID':req.session.id}, function(err, usersPostCountDB) {
if(usersPostCountDB){
userPostCount = req.body.postsCount + 1;
} else {
console.log('There was an error getting the postsCount');
}
});
I thought it should be able to find the userPostCount variable as it's the next level up in the scope chain.
Any ideas how I will be able to access it please? I need that variable to be outside of the function as I will be using it later for other mongoose activities.
I am getting the userPostCount as undefined.
Thanks in advance for the help!
PS: I looked around for other questions on SO but the solution on other answers don't seem to work for me.
Shayan
please use callbacks.
function getPostsCount(callback) {
userPostsModel.findOne({'profileID':req.session.id}, function(err, usersPostCountDB) {
if(usersPostCountDB) {
callback(null, req.body.postsCount + 1);
} else {
console.log('There was an error getting the postsCount');
callback(true, null);
}
});
}
and from outside call it by passing callback function as an argument. so the callback function will be executed right after getPostsCount() returns (finishes)..
getPostsCount(function(error, postsCount) {
if (!error) {
console.log('posts count: ', postsCount);
}
});
You are trying to return a value from a callback function. It's easier if you try to use the result inside the callback function.
Another thing you can do is you can define a function and give it a callback where you can use the value.
function foo(fn){
userPostsModel.findOne({'profileID':req.session.id}, function(err, usersPostCountDB) {
if(usersPostCountDB){
userPostCount = req.body.postsCount + 1;
fn(userPostCount);
} else {
console.log('There was an error getting the postsCount');
}
});
}
foo(function(userPostCount){
alert(userPostCount);
})
If you're using jquery, you can use deferred objects.
http://api.jquery.com/category/deferred-object/
Related
I have a question about the best way to chain callbacks together while passing data between them. I have an example below which works, but has the flaw that the functions have to be aware of the chain and know their position / whether to pass on a call back.
function first(data, cb1, cb2, cb3){
console.log("first()", data);
cb1(data,cb2, cb3);
}
function second(data, cb1, cb2) {
console.log("second()",data);
cb1(data, cb2);
}
function third(data, cb) {
console.log("third()",data);
cb(data);
}
function last(data) {
console.log("last() ", data);
}
first("THEDATA", second, third, last); // This work OK
first("THEDATA2", second, last); // This works OK
first("THEDATA3", second); // This doesn't work as second tries to pass on a callback that doesn't exit.
I can think of a number of ways around this, but they all involve in making the called functions aware of what is going on. But my problem is that the real functions I’m dealing with already exist, and I don’t want to modify them if I can avoid it. So I wondered if I was missing a trick in terms of how these could be called?
Thanks for the answers, and I agree that promises are probably the most appropriate solution, as they meet my requirements and provide a number of other advantages.
However I have also figured out how to do what I want without involving any extra modules.
To recap the specific ask was to:
chain together a number of functions via callbacks (this is so the first function can use a non-blocking I/O call the other functions are dependent upon),
while passing arguments (data) between them, and
without the existing functions having to be modified to be aware of their position in the callback chain.
The 'trick' I was missing was to introduce some extra anonymous callback functions to act as links between the existing functions.
// The series of functions now follow the same pattern, which is how they were before
// p1 data object and p2 is a callback, except for last().
function first(data, cb){
console.log("first()", data);
cb(data);
}
function second(data, cb) {
console.log("second()",data);
cb(data);
}
function third(data, cb) {
console.log("third()",data);
cb(data);
}
function last(data) {
console.log("last() ", data);
}
// And the named functions can be called pretty much in any order without
// the called functions knowing or caring.
// first() + last()
first("THEDATA", function (data) { // The anonymous function is called-back, receives the data,
last(data); // and calls the next function.
});
// first() + second() + last()
first("THEDATA2", function (data) {
second(data, function (data){
last(data);
}); // end second();
}); // end first();
// first() + third()! + second()! + last()
first("THEDATA3", function (data) {
third(data, function (data){
second(data, function (data){
last(data);
}); // end third();
}); // end second();
}); // end first();
Promises are the way to go as they provide following benefits :
Sequential callback chaining
Parallel callback chaining (kind of)
Exception handling
Easily passing around the objects
In general, a Promise performs some operation and then changes its own state to either rejected - that it failed, or resolved that its completed and we have the result.
Now, each promise has method then(function(result), function(error)). This then() method is executed when the Promise is either resolved or rejected. If resolved, the first argument of the then() is executed, with the result and if Promise gets rejected 2nd argument is executed.
A typical callback chaining looks like :
example 1 :
someMethodThatReturnsPromise()
.then(function (result) {
// executed after the someMethodThatReturnsPromise() resolves
return somePromise;
}).then(function (result) {
// executed after somePromise resolved
}).then(null, function (e) {
// executed if any of the promise is rejected in the above chain
});
How do you create a Promise at the first place ? You do it like this :
new Promise (function (resolve, reject) {
// do some operation and when it completes
resolve(result /*result you want to pass to "then" method*/)
// if something wrong happens call "reject(error /*error object*/)"
});
For more details : head onto here
Best practice would be to check whether the callback you are calling is provided in the args.
function first(data, cb1, cb2, cb3){
console.log("first()", data); // return something
if(cb1){
cb1(data,cb2, cb3);
}
}
function second(data, cb1, cb2) {
console.log("second()",data); // return something
if(cb1){
cb1(data, cb2);
}
}
function third(data, cb) {
console.log("third()",data); // return something
if(cb){
cb(data);
}
}
function last(data) {
console.log("last() ", data); // return something
}
first("THEDATA", second, third, last); // This work OK
first("THEDATA2", second, last); // This works OK
first("THEDATA3", second);
This will work fine.
Alternatively there are many more options like Promises and Async library e.tc
Maybe you want to try it this way, yes right using "Promise" has more features, but if you want something simpler, we can make it like this, yes this is without error checking, but of course we can use try / catch
function Bersambung(cb){
this.mainfun = cb
this.Lanjut = function(cb){
var thisss = this;
if(cb){
return new Bersambung(function(lanjut){
thisss.mainfun(function(){
cb(lanjut);
})
})
} else {
this.mainfun(function(){});
}
}
}
//You can use it like this :
var data1 = "", data2 = "" , data3 = ""
new Bersambung(function(next){
console.log("sebelum async")
setTimeout(function(){
data1 = "MENYIMPAN DATA : save data"
next();
},1000);
}).Lanjut(function(next){
if(data1 == ""){
return; // break the chain
}
console.log("sebelum async 2")
setTimeout(function(){
console.log("after async")
console.log(data1);
next();
},1000)
}).Lanjut();
Okay this might not be ideal but it works.
function foo(cb = [], args = {}) // input a chain of callback functions and argumets
{
args.sometext += "f";
console.log(args.sometext)
if (cb.length == 0)
return; //stop if no more callback functions in chain
else
cb[0](cb.slice(1), args); //run next callback and remove from chain
}
function boo(cb = [], args = {})
{
newArgs = {}; // if you want sperate arguments
newArgs.sometext = args.sometext.substring(1);
newArgs.sometext += "b";
console.log(newArgs.sometext)
if (cb.length == 0)
return;
else
cb[0](cb.slice(1), newArgs);
}
//execute a chain of callback functions
foo ([foo, foo, boo, boo], {sometext:""})
I have quite a simple problem, but I can't find an elegant solution to fix this.
In the following code, I have two nested calls to a mongo DB. I use Monk to manage my calls.
The problem is : the for loop (1) loops before the nested insertion can happen. So the next find (2) instruction does not find the last inserted action.
The call order is 1-2-2-2-3-3-3 (for an actionList of size 3). So all my data is inserted.
My objective is to have the call order 1-2-3-2-3-2-3
Do you have any clue of how to manage such a problem, without making a big find on my database and manage my list server-side ? (Get all data, make myself the search, that is quite horrible to do, insert elements I want, then push it all to the db...)
for (var action of actionList)//(1)
{
collectionActions.find(//(2)
{eventid : action.eventid},
function(e,actionsFound)
{
if (actionsFound.length == 0)
{
collectionActions.insert(action, function(err, result)//(3)
{
console.log("insert action : " + action._id);
})
}
}
)
}
The native Promise object has an all method that could be leveraged to help.
Assuming find is a compliant promise, the following code would queue up all of the actions in an array through map and which would return a promise for each action that eventually returns messages to the final then for all.
A couple of notes: your code as it stands swallows all of the errors that might occur (I'm not sure that is want you want); this also assumes that insert returns a promise.
Promise.all([
// Iterate over actionList
actionList.map(function(action) {
// returns a promise with a then already attached
return collectionActions.find({
eventid: action.eventid
}).then(function(e, actionsFound) {
if (actionsFound.length == 0) {
// returns another promise that will resolve up to outer promises
return collectionActions.insert(action, function(err, result) {
// Finally resolve a value for outer promises
return 'insert action : ' + action._id;
});
} else {
// A different value to resolve with if the above promise
// is not required
return 'some other message for ' + action._id;
}
});
})
]).then(function(results) {
// Log out all values resolved by promises
console.log(results);
});
UPDATE: After the clarification of the question it sounds like you just need to chain the promises together rather than run them in parallel.
// Iterate over actionList
actionList.reduce(function(promise, action) {
// Chain promises together
return promise.then(function(results) {
return collectionActions.find({
eventid: action.eventid
}).then(function(e, actionsFound) {
if (actionsFound.length == 0) {
// returns another promise that will resolve up to outer promises
return collectionActions.insert(action, function(err, result) {
// Finally resolve a value for outer promises
return results.push('insert action : ' + action.sourceName);
});
} else {
// A different value to resolve with if the above promise
// is not required
return results.push('some other message for ' + action.sourceName);
}
});
});
}, Promise.resolve([])).then(function(results) {
// Log out all values resolved by promises
console.log(results);
});
I finally got my solution, by using a recursive function.
var currentIndex = 0;
var searchAndInsert = function(actionList)
{
var action = actionList[currentIndex];
if (typeof actionList[currentIndex] != "undefined")
{
collectionActions.find(
{eventid : action.eventid},
function(e,actions)
{
console.log("find ended")
if (actions.length == 0)
{
collectionActions.insert(action, function(err, result)
{
console.log("insert action : " + action.sourceName);
currentIndex++;
if (typeof actionList[currentIndex] != "undefined")
searchAndInsert(actionList);
})
}
else
{
currentIndex++;
if (typeof actionList[currentIndex] != "undefined")
searchAndInsert(actionList);
}
}
)
}
};
I'm writing a NodeJS v0.10 application with MariaSQL.
i want to create a function that returns the id of a row, and if the row doesn't exist, to create it and then return the id.
this is what I have so far:
TuxDb.prototype.createIfNEDrinkCompany = function(drinkCompany) {
this.client.query("insert into drink_company(drink_company_name) values(:drink_company) on duplicate key update drink_company_id=drink_company_id",
{'drink_company' : drinkCompany})
.on('result',function(res) {
res.on('end',function(info){
if (info.insertId > 0) {
return info.insertId;
} else {
this.client.query("select drink_company_id from drink_company where drink_company_name = :drink_company",{'drink_company' : drinkCompany})
.on('result',function(res){
res.on('row',function(row){
return row.drink_company_id;
});
});
}
});
});
}
now the problem is that since it's asynchronous, the function ends before the value is returned.
how can I resolve this issue ?
The standard way in nodejs of dealing with async code is to provide a callback function as a last argument to your method and call it whenever your asynchronous finishes. The callback function standard signature is (err, data) - you can read more about here: Understanding callbacks in Javascript and node.js
Rewriting your code:
TuxDb.prototype.createIfNEDrinkCompany = function(drinkCompany, callback) {
this.client.query("insert into drink_company(drink_company_name) values(:drink_company) on duplicate key update drink_company_id=drink_company_id",
{'drink_company' : drinkCompany})
.on('result',function(res) {
res.on('end',function(info){
if (info.insertId > 0) {
callback(null, row.drink_company_id);
} else {
this.client.query("select drink_company_id from drink_company where drink_company_name = :drink_company",{'drink_company' : drinkCompany})
.on('result',function(res){
res.on('row',function(row){
callback(null, row.drink_company_id);
});
});
}
});
});
}
and then in the code calling your method
db.createIfNEDrinkCompany(drinkCompany, function(err, id){
// do something with id here
})
I am a newbie to node js and I am using mongoose for my models.
I have a function namde check which has a isNameThere function which receives name string as parameter in it. It checks the Db and looks for the name string which is provided if user exist in this name this.isNameThere will return true
var check= function()
{
this.nameIsThere = false;
this.isNameThere= function(name){
userModel.find({firstname: name},function(err,result){
if(result)
{
this.nameIsThere= true;
}
})
return this.nameIsThere;
}
}
Even if the name exist as you guess the code above will return false because the nature of asynchronous programming. Is there a way to execute the return isNameThere after userModel.find executes. Or any other solution for this situation. Thanks All.
Careful with the semicolons, you forgot some. It´s also good practice in JavaScript to place opening brackets right next to the function header and not in the next line.
You can encapsulate the DB call in a function like this:
function checkForName (callback) {
userModel.find({firstname: name}, callback);
}
checkForName(function (err, result) {
if (result) {
nameIsThere = true;
//do something else
...
}
});
After all, it IS anychronous, so you will not get any synchronous return value.
There´s also another way: Promises. Some libraries for you to check out:
https://github.com/caolan/async
https://github.com/kriskowal/q
I'm working with the parallel function in Async.js and for some reason the final call back is not getting executed and I do not see an error happening anywhere.
I'm dynamically creating an array of functions that are passed to the parallel call as such:
// 'theFiles' is an array of files I'm working with in a code-generator style type of scenario
var callItems = [];
theFiles.forEach(function(currentFile) {
var genFileFunc = generateFileFunc(destDir + "/" + currentFile, packageName, appName);
callItems.push(genFileFunc(function(err, results) {
if(err) {
console.error("*** ERROR ***" + err);
} else {
console.log("Done: " + results);
}
}));
});
async.parallel(callItems, function(err, results) {
console.log(err);
console.log(results);
if(err) {
console.error("**** ERROR ****");
} else {
console.log("***** ALL ITEMS HAVE BEEN CALLED WITHOUT ERROR ****");
}
});
Then in an outside function (outside of the function that is executing the forEach above) I have the generateFileFunc() function.
// Function that returns a function that works with a file (modifies it/etc).
function generateFileFunc(file, packageName, appName) {
return function(callback) {
generateFile(file, packageName, appName, callback);
}
}
I've looked at this SO post and it helped me get to where I'm at. However the final call back is not being executed. All of the items in the parallel call are being executed though. Inside of gnerateFile (function) at the very bottom I call the callback, so thats golden.
Anyone have any idea why this might not be executing properly?
The end result is to work with each function call in parallel and then be notified when I'm done so I can continue executing some other instructions.
Thanks!
Analyze what is happening line by line, starting with this:
var genFileFunc = generateFileFunc(...);
Since your function generateFileFunc returns function, so variable genFileFunc is a following function
genFileFunc === function(callback) {
generateFile( ... );
};
Now it is clear that this function returns nothing ( there is no return statement ). And obviously by nothing I understand JavaScript's built-in undefined constant. In particular you have
genFileFunc(function(err, results) { ... } ) === undefined
which is the result of calling it. Therefore you push undefined to callItems. No wonder it does not work.
It is hard to tell how to fix this without knowing what generateFile exactly does, but I'll try it anyway. Try simply doing this:
callItems.push(genFileFunc);
because you have to push function to callItems, not the result of the function, which is undefined.
Curious.
Best guess so far: Inside generateFile, RETURN callback instead of calling it.
You can achieve the stated goal with
async.map(theFiles, function(file, done) {
generateFile(destDir + "/" + file, packageName, appName, done);
}, function(err, res) {
// do something with the error/results
});