【问题标题】:How to catch this exception in promise? [duplicate]如何在承诺中捕捉到这个异常? [复制]
【发布时间】:2019-11-06 05:22:38
【问题描述】:

考虑以下代码:尤其是选择“无”时。使用 sweetalerts2

Swal.fire({ //
    html: '
    blah blah ',

    input: 'select',
    inputOptions: {
      'none': 'Please select an option:',
      'option1': 'First Option',
      'option2': 'Second Option'
    },
    inputValidator: function(value) {
      return new Promise(function(resolve, reject) {
        if (value != 'none') {
          resolve();
        } else {
          reject('You need to select an option');
        }
      });
    }
  }).then(function(theoption) {
      // etc etc...

选择“无”时,出现 javascript 错误。例如,在 Firefox 控制台上,我得到 “未捕获的异常:您需要选择一个选项” 我意识到我可能是一个绝望的新蜜蜂

【问题讨论】:

    标签: javascript jquery exception es6-promise sweetalert


    【解决方案1】:

    使用sweetalert时,错误信息需要resolve(),而不是错误信息reject(),因此,您需要将reject(...)更改为:

    resolve('You need to select an option');
    

    请看下面的例子:

    Swal.fire({
      html: 'blah blah ',
    
      input: 'select',
      inputOptions: {
        'none': 'Please select an option:',
        'option1': 'First Option',
        'option2': 'Second Option'
      },
      inputValidator: function(value) {
        return new Promise(function(resolve, reject) {
          if (value != 'none') {
            resolve();
          } else {
            resolve('You need to select an option');
          }
        });
      }
    }).then(function(theoption) {
      if (theoption.value) {
        Swal.fire('Great!');
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@8"></script>

    更多详情请参阅documentation

    【讨论】:

    • 多么糟糕的 API。 (不过,这是一个很好的答案。)
    猜你喜欢
    • 2016-10-05
    • 2014-12-03
    • 2015-12-19
    • 1970-01-01
    • 2020-12-17
    • 2010-12-21
    • 2019-08-20
    • 1970-01-01
    • 2012-03-20
    相关资源
    最近更新 更多