I'm having a hard time getting a chain of promises in a for loop to execute sequentially. I have an array and 5 functions that all return promises. For each element in the array, i'm creating 5 parameters and each parameter goes into each 5 functions which need to be executed sequentially before proceeding to the next item in the array. I need to promises to execute in the following manner.
- item 1
- func1(param1)
- If func1 succeeds continue to func2 else log errors and stop.
- If func2 succeeds continue to func3 else log errors ...
- item 2 ....
and so on.
const array = ['a','b','c','d','e']
evalParam(param,callback){
//do things with param
callback(true);
func1(param) {
return new Promise((resolve, reject) =>{
this.evalParam(param, resolve);
});
}
.
.
.
func5(param) {
return new Promise((resolve, reject) =>{
this.evalParam(param, resolve);
});
}
lastFunc(errors)
{
//Do things with errors
console.log(errors)
}
executeChain(array){
errors : any[] = []
return new Promise(resolve,reject) => {
return new Promise(resolve,reject) => {
for (let item of array){
const param1 = this.createParam1(item)
const param2 = this.createParam2(item)
const param3 = this.createParam3(item)
const param4 = this.createParam4(item)
const param5 = this.createParam5(item)
Promise.resolve()
.then(() => {
func1(param1) }
.then((val) => {
if (val) {
func2(param2)
} else {
errors.push("func1 failed with param: " + param1)
}
.
.
.
.then((val) => {
if (val){
func5(param5)
else {
errors.push("func5 failed with param: " + param5)
}
})
} // End for loop
.then(()=> {
resolve(errors)
})
}
Any help would be appreciated.