I’m pushing promises into an array so my function calls are scheduled, then wait with await Promise.all(promises);. It works fine, but if one function rejects, I want all of the promises to be cancelled as well… I can’t seem to figure it out. This is the code:
Server method:
async schedule(){
console.log("server schedule called");
try{
await schedule();
}catch(e){
console.log("Back in server, all work should stop now:",e);
return new Error("oep");
}
}
Imported code (server side):
const DELAYTIME = 1000;
const sleep = ms => new Promise(r => setTimeout(r, ms));
let conditions = [
"one",
"two",
"three",
"four",
"five"
];
async function funcOne(condition){
if(condition ==="three"){
reject();
}
console.log(condition);
}
export default async function schedule(){
let i = 0;
const promises = [];
for (const condition of conditions) {
i++;
(function(index, condition) {
promises.push(
sleep(index * DELAYTIME).then(async () => {
try{
await funcOne(condition);
}catch(e){
throw new Error("Stop all work");
}
})
);
})(i, condition);
}
await Promise.all(promises);
console.log("Finished");
}
The output is as follows:
I20231211-20:04:35.131(-4)? server schedule called
I20231211-20:04:36.132(-4)? one
I20231211-20:04:37.132(-4)? two
I20231211-20:04:38.154(-4)? Back in server, all work should stop now: Error: Stop all work
I20231211-20:04:38.154(-4)? at testScheduling.js:31:23
I20231211-20:04:39.134(-4)? four
I20231211-20:04:40.133(-4)? five