首页 > 解决方案 > 在链式承诺的每一步评估价值并打破承诺

问题描述

我有以下连锁承诺。在每一步,我都需要评估返回的值是否不为空。我可以在每一步添加一个 if else 条件,但我想知道是否有更简洁的方法来做到这一点。另外,如果值在任何一步都为空,我该如何跳出链条?

       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) => {
          ...
        })

标签: javascriptnode.jsvue.js

解决方案


你通过抛出一个错误打破了承诺链:

       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) => {
          ...
        })

推荐阅读