0

I am posting value But I am getting empty array . I know its node asynchronous problem . But I don't know how do i solve this. I have refer this following link:

How do I return the response from an asynchronous call?

But I could not able to understand . Kindly help me to understand promises and how do i use that in my code.

router.post('/inspection_list', function (req, res) {
    var id = req.body.project_id;
    console.log(id)
// res.send("ok")
    db.inspection.findOne({'_id':id},(err,response)=>{
        if(err){
            console.log("error");
        }
        else{
            console.log("Data")
            var inspection = [];
            var data = response.inspection_data;
      var f =  data.map(function (item) { 
                var fielduser = item.fielduser_id
                db.fielduser.findOne({'_id': mongoose.Types.ObjectId(fielduser)},(err,user)=>{
                    console.log(user.owner_name);
                    console.log(item.inspection_name)
                    inspection.push({inspection_name:item.inspection_name,field_user_name : user.owner_name})


                })
                });
console.log(inspection) // Here am getting empty value
           // setTimeout(function(){ console.log(inspection) }, 5000); my timeout code


        }
    })
});
9
  • Do you get values in var data? Commented Jul 6, 2018 at 7:16
  • What is the output of console.log(user.owner_name); and console.log(item.inspection_name) ? Commented Jul 6, 2018 at 7:18
  • Ya am getting the user name and inspection name in that.. if I set timeout function for console.log am getting the value Commented Jul 6, 2018 at 7:21
  • How about if you don't set time out? Can you post the time out code snippet as well? Commented Jul 6, 2018 at 7:23
  • 1
    Ya that's why I told that is asynchronous issue Commented Jul 6, 2018 at 8:11

2 Answers 2

2
router.post('/inspection_list', async function (req, res) {
    var id = req.body.project_id;
    try{
        var response = await db.inspection.findOne({'_id':id})
        var inspection = [];
        var data = response.inspection_data;
        for ( var i = 0; i<data.length; i++){
            var item = data[i]
            var fielduser = item.fielduser_id
            var user = await db.fielduser.findOne({'_id': mongoose.Types.ObjectId(fielduser)})
            inspection.push({inspection_name:item.inspection_name,field_user_name : user.owner_name})
       }
    }
    catch(err){
        throw err
    }
})

This uses async and await, you can use it if you are using node version >=7.6

Also note the following:

router.post('/inspection_list', async function (req, res)


Handling each error seperately

router.post('/inspection_list', async function (req, res) {
    var id = req.body.project_id;
    try{
        var response = await db.inspection.findOne({'_id':id})
    }
    catch(err){
        // handle error here
        throw err
    }
    var inspection = [];
    var data = response.inspection_data;
    for ( var i = 0; i<data.length; var item = data[i]
        var fielduser = item.fielduser_id
        try{
            var user = await db.fielduser.findOne({'_id': mongoose.Types.ObjectId(fielduser)})
        }
        catch(err){
             // handle error
        }            
        inspection.push({inspection_name:item.inspection_name,field_user_name : user.owner_name})
   }

})
Sign up to request clarification or add additional context in comments.

11 Comments

Check the query "router.post('/inspection_list', async function (req, res) "
add async there
I'll block text the async maybe then you'll get it
am getting empty only
|
0

Using mongoose would be the easy way out, it returns Promises for all query and save functions, so you'd simply do: YourModel.findOne({params}).then(() => {...})

If you're unable to do that, in your case, a 'promisified' example would be:

var findAndFillArray = (project_id) => new Promise((resolve) => {
    .... your previous code here .... 
    inspection.push({inspection_name:item.inspection_name,field_user_name : 
      user.owner_name})
    if (data.length === inspection.length){  // Or some other preferred condition
       resolve(inspection);
    }
})

Then you'd call this function after you get the id, like any other function:

var id = req.body.project_id;
findAndFillArray(id).then((inspection_array) => {
    res.send(inspection_array) // Or whatever
})

Now, map and all list functions are synchronous in JS, are you sure the error is due to that?

3 Comments

can't there be scenario where data.length === inspection.length doesn't hold? How will it be resolved then? And that's a valid scenario I think.
@eduPeeth I just placed a placeholder, he could whichever condition he wants, I'll edit the code with the comment
@eduPeeth Might even pass a reject param and add a reject condition in case some values are missing, now I have no actual knowledge of what the code should act like so I'll leave that up to the author :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.