2

I am new in Node.js and I want to pass data array to controller. But I am unable to insert for loop data in array and I also want to get result data out side function.

router.get("/list-group", function(req, res) {
    sess = req.session;
    var response = {};
    if (sess.loginData) {
        var TableData = [];
        var i = {};
        var result = [];
        mongoOp.users_group.find({
            group_id: req.query.group_id
        }, function(e, d) {
            var len = d[0].assign_user_id.length;
            var assignuserid = d[0].assign_user_id;
            for (var i = 0; i < assignuserid.length; i++) {

                var assignid = assignuserid[i];
                mongoOp.users.find({
                    _id: assignid
                }, function(err, data) {

                    // This is result array 
                    result[i] = data;

                })

            }
            // And I want to print result array here
            console.log(result);

        });

    } else {
        response = {
            "error": true,
            "message": "Invalid Login"
        };
        res.json(response);
    }
})
3
  • Reading this question may be helpful Commented Oct 13, 2018 at 11:56
  • At first you need a closure, stackoverflow.com/questions/750486/… . Commented Oct 13, 2018 at 16:08
  • Also do you want to do the work sequentially or asynchronously for different values of i? Commented Oct 13, 2018 at 16:12

2 Answers 2

1

I would make use of async and await

router.get('route', (req, res) => {
    // ...
    users.find(query, (err, d) => {
        try {
            // ...
            var results = []
            for (var data of array) {
                const result = await fetchUser(data)
                results.push(result)
            }
            console.log(results)
        } catch (err) {
            console.log('some error occured', err)
        }
    })
})

async function fetchUser(id) {
    return new Promise((resolve, reject) => {
        users.find({ _id: id }, (err, data) => {
            return err ? reject(err) : resolve(data)
        })
    })
}

If you're not that familiar with async and await I would recommend this video

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

Comments

0

u need read about async and callbacks in javascript. An alternative is read about async and await.

Comments

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.