Nodejs, wait for the current request to complete, then continue (or) wait for the first function to execute before moving on to the second function

I am using 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 completion firstfunction()and before receiving the value "ret", the second function is executed with the parameter "undefined", since "ret" is not yet available, which leads to an error.

How to perform the second function, only after the completion of the first function.

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;
    }
});

The function below should be executed only after the above is completed, that is, after receiving "myid".

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

Please show me the answer implementing my code. Thanks

+3
source share
2 answers

Node . , .

, , firstfunction, , , . , firstfunction ( , , ). secondfunction firstfunction(). - secondfunction firstfunction. :

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);

HTML, , , :

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

:

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

All Articles