【问题标题】:Node.js break promise chain [duplicate]Node.js打破承诺链[重复]
【发布时间】:2017-05-23 09:17:52
【问题描述】:

我试图通过在中间步骤之一不返回承诺来打破承诺链。

identity
.token(username, password)
})
.then((response) => {
  // Here I would like to break the promise chain.. HELP please..
  if (!token.tfa || !allow2FA)
    return res.status(200).json(token.raw);

  return twoFactor.generateLoginOtc(username, token);
})
.then((response) => {
  return res.status(204).json();
})
.catch((error) => {
  console.log(error);
  return res.status(error.status).json(error);
});

【问题讨论】:

    标签: node.js promise


    【解决方案1】:

    你不能很好地打破承诺链,但你可以嵌套它们:

    identity.token(username, password).then(response => {
      if (!token.tfa || !allow2FA) {
        return res.status(200).json(token.raw);
      }
      return twoFactor.generateLoginOtc(username, token).then(response => {
        return res.status(204).json();
      })
    }).catch(error => {
      console.log(error);
      return res.status(error.status).json(error);
    });
    

    【讨论】:

    • catch 是否也会处理twoFactor.generateLoginOtc 中的最终错误?
    • @Gabriel 是的,这会触发catch
    【解决方案2】:

    要打破承诺链,而不是returning,你需要throw 一些东西——通常是一个错误。

    .then((response) => {
      if (!token.tfa || !allow2FA) {
        res.status(200).json(token.raw);
    
        // throw error here
        throw new Error('Error message');
      }
    
      return twoFactor.generateLoginOtc(username, token);
    })
    .then((response) => {
      return res.status(204).json();
    })
    .catch((error) => {
      console.log(error);
      return res.status(error.status).json(error);
    });
    

    【讨论】:

    • 没有。那仍然会写两个响应。
    • 在这段代码中是的,它会在第一个then 中写入响应以及在catch 中的响应。如果 OP 不想这样做,那么显然需要删除其中之一。
    • 感谢您的回答,但我会接受第一个回答。我不想抛出错误,因为它不是一个。
    • @Aron 不,他确实想要令牌失败时的写入和 token()generateLoginOtc() 方法中发生错误时的写入。
    猜你喜欢
    • 2020-02-23
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 2015-08-21
    相关资源
    最近更新 更多