Javascript 使用bluebird链接多个请求

Javascript 使用bluebird链接多个请求,javascript,promise,bluebird,Javascript,Promise,Bluebird,我正在尝试使用BlueBird转换我现有的代码,请建议一个链接多个请求的最佳选项。每个回调中发生的错误需要重定向到具有不同错误的渲染 request(option1, function (error, response, body) { if (!error && response.statusCode == 200) { var data= JSON.parse(body); if(data.valid){ if(d

我正在尝试使用BlueBird转换我现有的代码,请建议一个链接多个请求的最佳选项。每个回调中发生的错误需要重定向到具有不同错误的渲染

request(option1, function (error, response, body) {
    if (!error && response.statusCode == 200) {
       var data= JSON.parse(body);

       if(data.valid){

           if(data.expired){

               next();
           } else {

               request(option2, function (error2, response2, body2) {
                 var data2= JSON.parse(body2);
                 if(data2.valid) {
                    request(option3, function (error3, response3, body3) {
                        next();
                    })
                 } else {
                    res.json({error:'Error1'});
                 }
               })

          }
        } else {
           res.json({error:'Error2'});
        }
     } else {
        res.json({error:'Error3'});
     }
})

这非常简单,还请注意,您当前的代码不会处理第二个和第三个请求中的错误,这会:

var request = require("request-promise"); // request - converted to bluebird

request(option1).then(data=> {
  if(!data.valid) throw Error("Error3");
  if(data.expired) return;
  return request(option2).then(JSON.parse);
}).then(data2 => {
  if(!data2) return; // didn't need to fetch additional data
  if(!data2.valid) throw Error("Error2");
  return request(option3);
}).then(() => {
  next();
}, e => {
  res.json(error: e.message); 
  // better log this. 
});
您不需要手动检查
statusCode
,但如果需要,首先必须将
resolveWithFullResponse
属性添加到
option1
对象中,该属性允许您接收
响应
对象:

function checkStatusCode(response) {
  if (response.statusCode !== 200) {
    throw Error('Error3');
  }
  return response.body;
}
// add resolveWithFullResponse attribute to option1
option1.resolveWithFullResponse = true;
rp(option1)
  .then(checkStatusCode)
  .then(parse)
  //...
function checkStatusCode(response) {
  if (response.statusCode !== 200) {
    throw Error('Error3');
  }
  return response.body;
}
// add resolveWithFullResponse attribute to option1
option1.resolveWithFullResponse = true;
rp(option1)
  .then(checkStatusCode)
  .then(parse)
  //...