我有以下连锁承诺。在每个步骤中,我需要评估返回的值是否不为null。我可以在每个步骤中添加一个if if条件,但是我想知道是否有更简洁的方法可以做到这一点。另外,如果该值在任何步骤为null,该如何跳出链条?
axios.post('/api/login', accounts)
.then((response) => {
this.nonce = response.data
return this.nonce
}).then((nonce) => {
let signature = this.signing(nonce)
return signature
}).then((signature) => {
this.verif(signature)
})
.catch((errors) => {
...
})
谢谢。
答案 0 :(得分:3)
通过抛出错误来打破承诺链:
axios.post('/api/login', accounts)
.then((response) => {
this.nonce = response.data
return this.nonce
}).then((nonce) => {
if (!nonce) throw ("no nonce")
let signature = this.signing(nonce)
return signature
}).then((signature) => {
if (!signature) throw ("no signature")
this.verif(signature)
})
.catch((errors) => {
...
})
答案 1 :(得分:2)
嵌套的诺言是不必要的。试试这个
axios.post('/api/login', accounts)
.then(async (response) => {
this.nonce = response.data
let signature = await this.signing(this.nonce);
if(!signature){
throw "invalid"
}
this.verif(signature);
.catch((errors) => {
...
})
答案 2 :(得分:1)
简洁起见,检查可能会用一个.then()
,因为抛出任何空值都会使检查失败。
axios.post('/api/login', accounts)
.then(async (response) => {
if(!response.data) throw "Response Error"
this.nonce = response.data
const signature = await this.signing(this.nonce);
if(!signature) throw "invalid"
this.verif(signature)
})
.catch((errors) => {
...
})