For some reason my promise is not being resolved on time. I can’t understand why, as my functions aren’t asynchronous.
What I’m trying to achieve is to go through an entire array and resolve a promise only after all the elements have been validated (If necessary)
So whenever the resolving conditions are met, I call promiseHelper = Promise.resolve(value)
. But for some reason I’m getting: Cannot read properties of undefined (reading 'then')
even though promiseHelper.then
is written after the recursive function, which means the helper
should be resolved before the then
statement.
My question is: Why does the variable come to that part of the code without being a promise? And if possible, what’s a better approach to achieve such functionality
Here’s the code:
const cart = req.body.items; //Array of items
let promiseHelper;
function recursiveCheck(cartIndex){
let pieceOutOfStock = Piece.find({nombre: cart[cartIndex].name, cantidad: {$gte:cart[cartIndex].amount}});
pieceOutOfStock.then(response =>{
if (!response.length){ //If nothing on the query, resolve as false
console.log("not enough:", element.amount, response.length);
promiseHelper = Promise.resolve(false);
return false;
}
else{
if(cart.length > cartIndex+1){ //If something on the query and items left, validate next item
recursiveCheck(cartIndex+1);
}
else{ //if last item, resolve as true
promiseHelper = Promise.resolve(true);
return true;
}
}
})
}
function getStock(){
return new Promise (resolve =>{
recursiveCheck(0);
promiseHelper.then(response =>{
if(!response){
resolve("reject")
}
else{
resolve("All good")
}
})
})
}
getStock().then(async response =>{
//do some stuff
}
Any help is appreciated
2
Answers
Update:
I found a work around for my code (still don't know the answer to the very first question tho)
response(resolve)
allows me send my info toquery
. And finally the deepest else statement acknowledges the end of the loop, so I just started my final process in there.Thanks all :)
await until u get the stock