Your Custom.find
method is asynchronous
so while your asynchronous
function is running to return a promise
the rest of your function outside the function runs as normal hence why you get an empty array returned, the code executes before your async function finished inside the loop to get the array with values outside the loop make your promise return a value which you can access later outside the loop
let promise = new Promise(function(resolve, reject) {
arr = [];
for (let i = 0; i < req.body.length; i++) {
var finalvalue=Customer.find({
'_id': req.body[i]
}).then(documents => {
console.log("name", documents[0].name);
arr.push(documents[0])
return arr
});
}
resolve(finalvalue)
});
promise.then(
result => {
console.log(result);
}
)
here is a working example
cutosm=(i)=>new Promise(r=>{
setTimeout(()=>{
r(i)
},300 +Math.random()*200)
})
async function smfunc(){
arr = [];
for (let i = 0; i < 8; i++) {
var finalvalue= await cutosm(i).then(e => {
arr.push(e)
return arr
});
}
return finalvalue
}
smfunc().then(r=>console.log(r))