0

I have an array of values, i need to run a for loop to run a query and extract some more values from it.

var output = [];
for(var x=0; x<somevaluesArray.length; x++){
 XModel.findOne({
    name: somevaluesArray[x].name
 })
 .then(function(doc){
    output.push(doc.name)
 })
 .catch(function(err){
    console.log(err);
 });
}
console.log(output);

i need the output array outside the for loop to contain the pushed values, please suggest me a way to get this running. Thanks in advance.

foxenn_pro
  • 71
  • 9
  • See the linked question's answers for why the above doesn't work. In this specific case, here's how you can apply those answers to the above: `Promise.all(somevaluesArray.map(({name}) => XModel.findOne({name}))).then(output => { /* Use output here */ }).catch(err => { /* Handle error here */ });` That: 1. Maps the array values to promises from `findOne`. 2. Uses parameter destructuring (`({name}) =>`) because all we need from each array entry is the name. 3. Uses shorthand properties (`findOne({name})`). 3. Uses `Promise.all` to wait until all those promises complete (or the first fails). – T.J. Crowder Jan 26 '18 at 08:29
  • Thank you sir, will sure see to it. – foxenn_pro Jan 26 '18 at 08:33

0 Answers0