I have the following chained promise. At each step, I need to evaluate if the returned value is not null. I can add an if else condition at each step, but I was wondering if there is a more concise way of doing this. Also, how can I break out of the chain if the value is null at any step?
JavaScript
x
14
14
1
axios.post('/api/login', accounts)
2
.then((response) => {
3
this.nonce = response.data
4
return this.nonce
5
}).then((nonce) => {
6
let signature = this.signing(nonce)
7
return signature
8
}).then((signature) => {
9
this.verif(signature)
10
})
11
.catch((errors) => {
12
13
})
14
Advertisement
Answer
You break out of the promise chain by throwing an error:
JavaScript
1
16
16
1
axios.post('/api/login', accounts)
2
.then((response) => {
3
this.nonce = response.data
4
return this.nonce
5
}).then((nonce) => {
6
if (!nonce) throw ("no nonce")
7
let signature = this.signing(nonce)
8
return signature
9
}).then((signature) => {
10
if (!signature) throw ("no signature")
11
this.verif(signature)
12
})
13
.catch((errors) => {
14
15
})
16