Saturday, 10 June 2017

storing the output of the callback function to an external variable in node js

i am trying to store the output from a callback (find) function in node js to a variable which ill be adding to an array .since I am using a loop for all this i am facing problem in retrieving the variable as it comes out to be undefined everytime .Please help to rectify the code below.

var relations = []
      relconf.find({"pId":req.params.pId},'termType form',function(err, terms) {
        if (err) {
          console.log(err)
        } else {
            console.log(terms+"###########")
             terms.forEach(function(value){
            for(var i = 0;i<value.form.length;i++){
                var ExpectedRels =value.form[i].expectedRelation
                value.form[i].property.forEach(function(value){
                //console.log(value.dataField+"@"+value.type)
            })
                var termId=value.form[i].termType
      //    retrieveUser(termId,req.params.pId,handleResult);
                **var termname= retrieveUser(termId,req.params.pId,function(err,name){
                    name
                });**
                console.log(termname+"__________________________________________-")
                relations.push({"name":termname,"Expected Relations":ExpectedRels})
                //console.log(relations)
            }
             })
         res.send (relations)   
        }
      });

in this case console .log shows the following result for termname: undefined__________________________________________- undefined__________________________________________- by callback function is as follows :

function retrieveUser(term, Pid,callback) {
      relconf.findOne({"pId": Pid},'termType',function(err, users) {
        if (err) {
          callback(err, null);
        } else {
            //console.log(users)
            for(var i = 0;i<users.termType.length;i++){
                if(users.termType[i].id==term){
                    callback(null, users.termType[i].name);
                }
            }

        }
      });
    };

My whole motive is to have the value of 'name' from callback stored in the variable termname so that it can be added to the array.



via Nitika Jain

No comments:

Post a Comment