0
var user_id = '98-XXXXXXXX'

Contact.find({user_id: user_id})
.exec(function (err, results) {
  if (err) { 
    return next(err); 
  }
    var finalArray = [];
    for(var i = 0; i< results[0].Total; i++) {

      if(results[0].Contacts[i].name != "SPAM") {

       for(var j = 0; j < results[0].Contacts[i].phoneNumbers.length; j++){

           var number = results[0].Contacts[i].phoneNumbers[j].number
           number = number.replace(/ /g,'');
            var user_id = number.substr(number.length - 10); 

                Login.find({user_id:user_id})
                .exec(function(err,results) {
                if(err) {
                return next(err); }

                    var intCount = results.length;
                        if (intCount > 0)
                        {
                            console.log('called')
                            finalArray.push(results[0])
                            console.log(finalArray)
                        } 
               });

            }
         }

        //console.log(i,results[0].Total - 1);
        //if(i == results[0].Total - 1)



    } 
                    console.log('Ended Here',finalArray)
                    var responseTosend = {"message":finalArray,"user_id":user_id}
                    return  res.send(responseTosend);

});

EndedHere[] this is coming up first empty, after that i got the result of login.find query which is correct. Any ideas how to get the finalArray after all the calculation. Thanks in advance

2 Answers 2

1

Since the functions are returning promises within the loops, the code execution has to wait till all those promises are resolved. Consider using Promise.all or Promise.map to wait. Reference

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

1 Comment

I am new to nodeJS can you please give a snippet of code for a reference how it really works
0

As already mentioned, a structure like this, will not return the results, but the intermediate functions or objects before they are finished, since nodejs does not know it should await the results first.

const x = [1,2,3]
let results = []

for (let i = 0; i < x.length; i++){
  results.push(someAsyncJobLikeADatabaseCall(x[i]))
}

// this will not return the results, but the intermediate async objects/functions
console.log(results)

Here is a better version using promises and the .map function. Notice, how we replaced the for loop with .map() (which you could see as a shorthand for .forEach + push() or for() + push(). Mongoose returns Promises if configured right, so you don't even have to manually define them and we can directly return them in .map.

const x = [1,2,3]
let results = []

async function getAsyncResults(array){
  // map returns an array, this time, an array of promises
  const promises = x.map(number => someAsyncJobLikeADatabaseCall(number))
  // Promise.all resolves, if all promises in the array have been resolved
  return Promise.all(promises)
}

try {
  let results = await getAsyncResults(x)
  // this will return the results you expect.
  console.log(results)
} catch (err) {
  console.log('Some error', err)
}

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.