Nodejs , wait until current request completes, then proceed (or) wait until firstfunction executes before going to second function

I use nodejs code:

var ret = firstfunction();  //this calls database and gets some return value
var output = secondfunction(ret); // in this function we used ret as parameter 

Before firstfunction() completes , and before it gets the value "ret", the second function executes with parameter "undefined" as "ret" is not yet available resulting in an error .

How can i execute second function, only after first function completes execution.

var uname = "sachin";
var noqq=UserModel.find({uname:uname},function(err,user){
if(!err){
    myid=user[0]._id;  //SAVING myid here , I AM USING THIS IN THE NEX FUNCTION
    return myid;
}else { 
     return null;
    }
});

Below function should execute only after above one completes, that is after getting "myid" only.

var ret=CollegeModel.findById(myid, function(err,colleges){
if(!err)
{
    res.send(questions);
}
else {
    res.send(err);
}
});

Please show me answer implementing my code. Thanks

With Node, you have to learn to do things asynchronously. You can use its many synchronous methods, but you lose out on the benefits of going fully non-blocking.

So without knowing what's in firstfunction, you probably have an asynchronous method in there. If so, firstfunction is returning before the asynchronous method is returned (internally, it's probably not even been invoked). What you need to do is send your secondfunction into firstfunction(). The simplest way to do that is to pass secondfunction as an argument to firstfunction. Your code will look something like this:

var firstfunction = function(myCallback) {
    var dbSuccessCallback = function(returedData) {
        // the asynchronous call has retured successfully with data

        myCallback(returnedData); 
    };
    callDatabase("SELECT a FROM b", dbSuccessCallback);
}


firstfunction(secondfunction);

If you do event binding in HTML, you're already probably very used to doing this:

mydiv.addEventListener('click',function(){/* Do something */}, true);

or another way:

var myCallback = function(){
    /* Do something */
};
mydiv.addEventListener('click',myCallback, true);

Look into the node-async library for some nice wrappers around common patterns for things like this: https://github.com/caolan/async

It sounds like either series or waterfall would work well for your use case.