0

Here i am receiving a set of token in csv texts and every token belongs a document in monogdb. My logic is to get the documents token wise and return them as an array to the front end .

Here I have done this but its returning an empty error instead of array of objects.

var helps = [];
        const token_list = req.body.token_list;
        let splittedtoken = token_list.split(",");
        splittedtoken.shift();
        console.log(splittedtoken);
        splittedtoken.forEach(token => {
            Help.find({ 'token': token }, (err, result) => {
                if (result) {
                    helps.push(result[0])
                }
            });
            console.log(helps);
        })`

i am unable to solve it , any kind suggestions are heartly welcome . Thanks

1
  • Help is your db collection. It's async but forEach is not async Commented May 22, 2021 at 21:03

1 Answer 1

1

Databse operations are async but forEach is not.

You can use Promise.all to achieve it. First, push all db operations to an array and then use Promise.all to retrieve it's results.

var helps = [];
const token_list = req.body.token_list;
let splittedtoken = token_list.split(",");
splittedtoken.shift();
console.log(splittedtoken);

let promises = [];

splittedtoken.forEach(token => {

  promises.push(new Promise((resolve, reject) => Help.find({
    'token': token
  }, (err, result) => {
    if (result) {
      resolve(result[0])
    }
  })));

});

Promise.all(promises).then(results => console.log(results)).catch(e => console.log(e));

Do note that, Promise.all is all or nothing. If a single promise was rejected, the entire operation will fail and catch block will execute.

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

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.