我有以下的承诺。 在每一步,我都需要评估返回的值是否不为空。 我可以在每一步添加一个if else条件,但我想知道是否有一种更简洁的方法来实现这一点。 还有,在任何一步,如果值为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) => {
...
})
谢谢。 J。
您通过抛出一个错误来打破承诺链:
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) => {
...
})
嵌套承诺是不必要的。 试试这个
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) => {
...
})
简明性,它可能是一个.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) => {
...
})