【问题标题】:How to break out of a promise (.then) statement javascript如何打破承诺(.then)声明javascript
【发布时间】:2023-04-03 03:26:01
【问题描述】:

当 catch 语句中发生错误时,我在尝试中断 promise 语句时遇到问题。

我不确定是否可以在 catch 语句中抛出错误。

问题:当我抛出错误时,catch 函数没有做任何事情。

预期结果:catch 语句显示警报并中断承诺链。

代码

        if (IsEmail(email)) {
        $('body').loadingModal({
              position: 'auto',
              text: 'Signing you in, please wait...',
              color: '#fff',
              opacity: '0.9',
              backgroundColor: 'rgb(0,0,0)',
              animation: 'doubleBounce'
        });

        var delay = function(ms){ return new Promise(function(r) { setTimeout(r, ms) }) };
        var time = 2000;

        delay(time)
        .then(function() { $('body').loadingModal('animation', 'foldingCube'); return delay(time); } )
        .then(function() { 
            firebase.auth().signInWithEmailAndPassword(email, password)
            .then(function () {
                var user = firebase.auth().currentUser;
                uid = user.uid;
                configure();
            })
            .catch(function(error) {
                throw error;
            });
        })
        .then(function() { $('body').loadingModal('color', 'white').loadingModal('text', 'Welcome to Dtt deliveries').loadingModal('backgroundColor', 'orange');  return delay(time); } )
        .then(function() { $('body').loadingModal('hide'); return delay(time); } )
        .then(function() { $('body').loadingModal('destroy') ;} )
        .catch(function(error) {
            alert("Database error: " + error);
        }); 
    }
    else {
        alert("Please enter a valid email");
        return;
    }

【问题讨论】:

    标签: javascript promise break out


    【解决方案1】:

    delay 之后的第二个.then 立即解析,因为它没有返回任何内容。而是返回 signInWithEmailAndPassword 调用,因为它返回一个 Promise,您需要将它与外部 Promise 链链接在一起:

    .then(function() {
      return firebase.auth().signInWithEmailAndPassword(email, password)
      // ...
    

    此外,捕捉并立即抛出并没有真正做任何事情 - 除非您需要处理特定于 signInWithEmailAndPassword 的错误,请随意完全省略 catch

    delay(time)
      .then(function() { $('body').loadingModal('animation', 'foldingCube'); return delay(time); } )
      .then(function() { 
        return firebase.auth().signInWithEmailAndPassword(email, password)
      })
      .then(function () {
        var user = firebase.auth().currentUser;
        uid = user.uid;
        configure(); // if configure returns a Promise, return this call from the `.then`
      })
      .then(
      // ...
      .catch(function(error) {
        alert("Database error: " + error);
      });
    

    如果configure 也返回了一个 Promise,那么你也需要返回它。 (如果是同步的就不需要了)

    (您也可以考虑使用更用户友好的方式来显示错误,也许使用适当的模态而不是alert

    另一个要考虑的选项是使用await 而不是所有这些.thens,控制流可能更清晰:

    (async () => {
      if (!IsEmail(email)) {
        alert("Please enter a valid email");
        return;
      }
      $('body').loadingModal({
        position: 'auto',
        text: 'Signing you in, please wait...',
        color: '#fff',
        opacity: '0.9',
        backgroundColor: 'rgb(0,0,0)',
        animation: 'doubleBounce'
      });
    
      var delay = function(ms) {
        return new Promise(function(r) {
          setTimeout(r, ms)
        })
      };
      var time = 2000;
    
      try {
        await delay(time);
        $('body').loadingModal('animation', 'foldingCube');
        await delay(time);
        await firebase.auth().signInWithEmailAndPassword(email, password)
        var user = firebase.auth().currentUser;
        uid = user.uid;
        configure(); // if this returns a Promise, `await` it
        $('body').loadingModal('color', 'white').loadingModal('text', 'Welcome to Dtt deliveries').loadingModal('backgroundColor', 'orange');
        await delay(time);
        $('body').loadingModal('hide');
        await delay(time);
        $('body').loadingModal('destroy');
      } catch(error) {
        alert("Database error: " + error);
      }
    })();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-23
      • 2018-03-18
      • 2012-08-22
      • 2020-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多