【问题标题】:Evaluate Value at Each Step of a Chained Promise and Break Out of Promise在链式承诺的每一步评估价值并打破承诺
【发布时间】:2020-08-03 13:26:58
【问题描述】:

我有以下链式承诺。在每一步,我都需要评估返回的值是否不为空。我可以在每个步骤中添加一个 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) => {
          ...
        })

【问题讨论】:

    标签: javascript node.js vue.js


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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) => {
                ...
              })
      

      【讨论】:

      • 感谢您的回答vpdiongzon。
      【解决方案3】:

      简明起见,它可能是一个.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) => {
                ...
              })
      

      【讨论】:

      • 没问题!如果这不起作用,请告诉我,我相信我们可以解决! :)
      猜你喜欢
      • 2020-02-23
      • 1970-01-01
      • 2017-11-23
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多