I am working on a promise chain that was inspired by this answer: https://stackoverflow.com/a/44955506/7485805
I want to break this for loop in order to properly handle the rejection of the chain. I just figured that I can't use break
inside the .catch
method of the chain.
Here's my code if it helps:
function pro (arr) {
let chain = Promise.resolve();
const self = {req: {}, res: {}};
const length = arr.length;
return new Promise((resolve, reject) => {
for(let i=0; i<length; i++){
chain = chain
.then(() => arr[i].call(self) )
.then(() => {
if(i === (length - 1) )
resolve();
})
.catch(e => {
reject(e);
})
}
})
.then(() => {
return self
})
.catch(e => {
throw new Error (e);
})
}
const x = function () {
const self = this;
return new Promise(resolve => {
self.req = {key: "value"}
resolve();
})
}
const y = function () {
const self = this;
return new Promise((resolve, reject) => {
console.log(self);
reject();
})
}
const z = function () {
const self = this;
return new Promise((resolve, reject) => {
console.log('failed');
})
}
pro([x, y, z])
.then((self) => {
console.log('final',self);
})
.catch(e => {
console.log('error', e);
})
x, y, z
are three functions chained together in function pro
While, x
resolves successfully, y
is executed but gets rejected.
I want to stop the execution of z
since it's pointless to continue and may produce error in actual code.
Also, if someone can recommend me a better version for this piece of code:
.then(() => {
if(i === (length - 1) )
resolve();
})
Note: I cannot use await
since this code will be executed server-side and use of await
may block other incoming requests.