打破承诺链 - 停止下一个'然后'从执行

时间:2017-10-06 17:00:59

标签: node.js express asynchronous promise

我正在Node / Express中编写注册系统,我正在尝试使用Promises。

问题是我在使用它时收到错误消息:

错误:

  

(node:64725)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:2):

有没有办法停在then

auth.isRegistered(email)
.then((registered) => {
    if ( !registered ) {
        req.flash('pleaseRegister', 'Looks like you haven\'t registered. Please register first.');
        req.session.user = user;
        res.redirect('/register')
    }
})
.then(() => {
    return auth.isVerified(email);
})
.then((verified) => {
    if ( !verified ) {
        console.log('please verify');
        res.redirect('/register/verify');
    } else {
        req.login(user, err => {
            if ( err ) return next(err);
            req.session.timestamp = Date.now();
            auth.updateLastLogin(email)
            .then(() => {
                res.redirect(req.session.returnTo || '/account');
            });
        });
    }
});

4 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

  1. 当您想要破坏承诺链时,抛出自定义错误。
  2. 签入catch回调,抛出错误是自定义错误。如果是,请继续,否则使用next对象
  3. 调用error

    示例:

    let getBreackChainError = () => {
      let err = new Error();
      err.name = 'BreackChainError';
      return err;
    };
    
    auth
      .isRegistered(email)
      .then(registered => {
          if (!registered) {
            req.flash('pleaseRegister', 'Looks like you haven\'t registered. Please register first.');
            req.session.user = user;
            res.redirect('/register');
            throw getBreackChainError();
          }
          return auth.isVerified(email);
      })
      .then(verified => {
          if (!verified) {
            console.log('please verify');
            res.redirect('/register/verify');
            throw getBreackChainError();
          }
          return new Promise((resolve, reject) => {
            req.login(user, err => {
              if (err) {
                return reject(err);
              }
              req.session.timestamp = Date.now();
              resolve();
            });
          });
      })
      .then(() => auth.updateLastLogin(email))
      .then(() => res.redirect(req.session.returnTo || '/account');
      .catch(err => {
        if (err.name !== 'BreackChainError') {
          next(err);
        }
      });
    

    注意。你不应该将回调与promises混合使用。在上面的示例中,我宣传 req.login,所以现在它返回一个承诺。

答案 1 :(得分:1)

语言:JavaScript

为简单起见,只需使用:- (以防您不想进一步处理错误)

throw new Error("An error occured");

示例:- (fetch)

fetch("endpoint/resource", requestOptions)
        .then(response => {
            if(response != null && response.status == 404) {
                throw new Error("RECEIVED NULL OBJECT");
            }
            return response;
        })
        .then(approvedResponse => approvedResponse.blob())
.catch(e => console.log(e));

答案 2 :(得分:-1)

UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:2): 我相信这是因为你没有办法处理你的初始.thens中的错误,因此你得到了上述错误。它不是"停止" .then,但正确处理错误。你可以做(​​错误)=> {return}基本上会停止"停止"但它在你的应用程序中的流量控制。

答案 3 :(得分:-2)

当你想要“停止”承诺时,你必须return。或Promise.resolvePromise.reject()

在这种情况下例如:

if ( !registered ) {
  req.flash('pleaseRegister', 'Looks like you haven\'t registered. Please register first.');
  req.session.user = user;
  return res.redirect('/register')
}