1

We are using async and await to collect the count from another function but getting Promise Issues, We know to use then() but need to update outer array/object.

How can we wait still update forEach element and push to the array?

sample code :

module.exports = {
    getQuestionCounts: function(req, res){ // connected with Routes
        var arr = [];
        req.data.forEach(element => {
            module.exports.getCounts(element).then(function(count){
                console.log(count); // getting value
                element.count = count; 
                arr.push(element); // not updating with array
            });                  
        });           
        if(arr.length > 0){ // other operations }
    }
    getCounts: async function(data){
        var count = await Questions.countDocuments({"object":{$elemMatch: {data}}}).then(function(result){
            return result;
        });
        console.log(count); // getting count Fine
        return count;
    }
}
151291
  • 3,308
  • 7
  • 48
  • 81
  • Got soultion : Find much helpful to solve my issues using [this](http://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404) – 151291 Apr 14 '19 at 06:22

1 Answers1

0

getCounts returns a Promise so you can use .then callback or async/await

getQuestionCounts: function(req, res){
  var arr = [];
  // not sure why you're doing this way
  module.exports.getCounts(req.data).then(data => {
    // data is available only here
    console.log(data);
    arr.push(data)
    // use arr here
  })
  // arr will be empty
  console.log(arr)
}

async/await

getQuestionCounts: async function(req, res){
  try {
    var arr = [];
    var count = await module.exports.getCounts(req.data);
    arr.push(count);
  } catch (e) {
    //handle error
    console.error(e)
  }
}

Note: All async function returns Promise

Preferable way to use module.exports

function someFunc() {
  return something;
}

function anotherFunc() {
  const result = someFunc()
  // do something
  return another;
}

module.exports = {
  // if you still want to export someFunc
  someFunc
  anotherFunc
}
1565986223
  • 6,420
  • 2
  • 20
  • 33
  • We can no set `getQuestionCounts`, we need a count out of `then` or need to update the `arr` for every loop and pass `arr` to another manipulation. – 151291 Apr 12 '19 at 13:06
  • Updated my Question for better understanding with my requirements. – 151291 Apr 12 '19 at 13:16