Reputation: 31
I'm trying to break a loop inside a sequelize promise when it finds its first result and returns the first response, but it always do the entire loop. If I assign a value to a variable inside the promise, the value disappears outside. I've trying very hard for days and I will really appreciate if anyone can help me. This is my code:
for (let i = (parseInt(req.query.units) - 1); i >= 0; i--) {
console.log (i);
db.order_planned.findAll({
where: {
barcode: parseInt(req.query.barcode) + i,
stepdesc: req.query.stepdesc
},
limit: 1,
}).then((data) => {
if (data[0].length > 0) {
data[0].barcode = (parseInt(data[0].barcode) - i);
console.log(data[0]);
res.status(200).json(data[0]);
break; // illegal break
}
}).catch((error) => {
let err_msg = new ErrorMsg(error);
res.status(err_msg.status).json(err_msg);
});
}
Upvotes: 1
Views: 214
Reputation: 2187
You want to loop over n promises and return the first promise that resolves. Promise.any() does just that.
Using a simplified version of your code:
const promises = [];
for (let i = (parseInt(req.query.units) - 1); i >= 0; i--) {
promises.push(
db.order_planned.findAll({ /*..*/ }).then((data) => {
/*..*/
return data[0]; // Found your data
});
);
}
// As soon as the first promise is returned, log it.
Promise.any(promises).then(firstResult => console.log(firstResult));
Because of the way promises work, the loop will always execute in it's entirety before any promises are returned.
Alternatively, you can use async/await to get what you desire:
for (let i = (parseInt(req.query.units) - 1); i >= 0; i--) {
const data = await db.order_planned.findAll({ /*..*/ }); // Use await here
if (data[0].length > 0) {
/*..*/
break; // Can now do a break here
}
}
However, this will have worse performance because the promises are not executed in parallel.
Upvotes: 2