如何正确的链承诺互相依赖的电话?

我有以下代码:

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) }) 

我会build议尽早失败,这意味着首先处理错误条件,并有意义的错误消息,以便能够logging他们,如果需要的话。 最后,您可以传播错误,并在一次捕获中处理它。 把它放在代码中的上下文中:

 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'); });