如何适当地调用相互依赖的链式承诺调用?

How to proper chain promises calls that depend on one another?

我有以下代码:

const request = require('request-promise');

request(validateEmailOptions).then(function(result) {
  if (result.valid) {
    request(createUserOptions).then(function (response) {
      if (response.updatePassword) {
         request(modifyUserOptions).then(function (response) {
          return res.redirect('/signin');
        }).catch(function(error) {
          return res.redirect('/error');
        });
      }
    }).catch(function(error) {
      return res.redirect('/error');
    });
  } else {
    return res.redirect('/error');
  }
})
.catch(function (reason) {
  return res.redirect('/error');
});

基本上,这是一个请求调用链,每个请求调用都基于前一个调用的结果。问题是我在每个条件下都有更多行,因此我的代码臃肿且难以阅读和遵循。我想知道是否有更好的方法来使用请求承诺或简单地请求和蓝鸟来编写调用链。

您可以解除承诺。认为这个:

f(a).then(function(a) {
  return g(b).then(function(b) {
    return h(c)
  })
})

等同于:

f(a).then(function(a) {
  return g(b)
}).then(function(b) {
  return h(c)
})

我建议尽早失败,这意味着首先处理错误情况,并有有意义的错误消息以便能够在需要时记录它们。最后,您可以传播错误并在单个捕获中处理它。将其置于代码的上下文中:

request(validateEmailOptions).then(function(result) {
  if (!result.valid) {
    throw new Error('Result is not valid');
  }
  return request(createUserOptions);
}).then(function(response) {
  if (!response.updatePassword) {
    throw new Error('Password is not updated');
  }
  return request(modifyUserOptions);
}).then(function(response) {
  return res.redirect('/signin');
}).catch(function(error) {
  // you may want to log the error here
  return res.redirect('/error');
});