I am trying to create an array of promises so I can batch promises instead of executing them all together to avoid shutting down my server. I want to execute up to 20 promises at a time. I have written the following code:
let promises = [];
let create;
let update;
let i=0;
let users = users.json;
if (users && usersjson.users.length) {
for (const user of users) {
if (userexists) {
update = new promise(async (resolve,reject) => {
//Function to update user
});
promises.push(update);
i++;
} else {
create = new promise (async (resolve,reject) => {
//Function to create a new user
});
promises.push(update);
i++;
}
if (promises.length >= 20 || i >= usersjson.users.length) {
await Promise.all(promises)
.then((response)=>{
console.log(response);
promises=[];
}).catch((err)=> {
console.log(err);
})
}
}
}
However, I found that the promises are executed when I define them, instead of being pushed into the array and executed when I call Promise.all, and I can't figure out why.
I would also prefer to have the Promise.all function continue to run even if a single promise was rejected, if that's possible with the way my code is built. I have a catch inside each promise in case the code fails, is that the correct way to do that?