I have written a class to capture a microservice accessed vi https. Several calls have been implemented in asynchronous methods which all work fine by themselves (here: step1(), step2(), step3()).
However I want to call a few of those in succession (run()) to implement certain workflows.
What I can not manage so far is that the stepX methods get called after another. Also I want to call run() and get a promise back so I can .then() when all is done. Also I want to implement some error handling there to catch all errors that might occur during the chain.
Here's a class that reduces my problems to the core:
class Foo {
run() {
return this.step1()
.then(() => this.step2())
.then(() => this.step3())
}
step1() {
console.log('1')
return new Promise(function(resolve) {
setTimeout(function(){console.log('2')}, 500)
});
}
step2() {
console.log('3')
return new Promise(function(resolve) {
setTimeout(function(){console.log('4')}, 500)
});
}
step3() {
console.log('5')
return new Promise(function(resolve) {
setTimeout(function(){console.log('6')}, 500)
});
}
}
let bar = new Foo();
bar.run()
.then(console.log('7')) // react on run() finishing successfully
.catch(err => console.log('err:', err)) // global error handling
I expected this to output the numbers 1 to 7 in correct order. However the current output is
1
7
2
Thank you for any help! Christian