Javascript node.js+;请求=>;node.js+;蓝鸟&x2B;要求

Javascript node.js+;请求=>;node.js+;蓝鸟&x2B;要求,javascript,node.js,promise,bluebird,Javascript,Node.js,Promise,Bluebird,我试图理解如何用承诺编写代码。 检查我的密码。这是对的 Node.js+请求: request(url, function (error, response, body) { if (!error && response.statusCode == 200) { var jsonpData = body; var json; try { json = JSON.parse(jsonpData);

我试图理解如何用承诺编写代码。 检查我的密码。这是对的

Node.js+请求:

request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var jsonpData = body;
        var json;
        try {
            json = JSON.parse(jsonpData);
        } catch (e) {
            var startPos = jsonpData.indexOf('({');
            var endPos = jsonpData.indexOf('})');
            var jsonString = jsonpData.substring(startPos+1, endPos+1);
            json = JSON.parse(jsonString);
        }
        callback(null, json);
    } else {
        callback(error);
    }
});
request.getAsync(url)
   .spread(function(response, body) {return body;})
   .then(JSON.parse)
   .then(function(json){console.log(json)})
   .catch(function(e){console.error(e)});
Node.js+蓝鸟+请求:

request(url, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        var jsonpData = body;
        var json;
        try {
            json = JSON.parse(jsonpData);
        } catch (e) {
            var startPos = jsonpData.indexOf('({');
            var endPos = jsonpData.indexOf('})');
            var jsonString = jsonpData.substring(startPos+1, endPos+1);
            json = JSON.parse(jsonString);
        }
        callback(null, json);
    } else {
        callback(error);
    }
});
request.getAsync(url)
   .spread(function(response, body) {return body;})
   .then(JSON.parse)
   .then(function(json){console.log(json)})
   .catch(function(e){console.error(e)});

如何检查响应状态?我应该使用if from first example或其他更有趣的方法来检查状态代码:

.spread(function(response, body) {
  if (response.statusCode !== 200) {
    throw new Error('Unexpected status code');
  }
  return body;
})

您只需检查
响应.statusCode
扩展处理程序中是否不是200,并从中抛出
错误,以便
捕获处理程序处理它。您可以这样实现它

var request = require('bluebird').promisifyAll(require('request'), {multiArgs: true});

request.getAsync(url).spread(function (response, body) {
    if (response.statusCode != 200)
        throw new Error('Unsuccessful attempt. Code: ' + response.statusCode);
    return JSON.parse(body);
}).then(console.log).catch(console.error);

如果您注意到,我们将从
spread
处理程序返回解析后的JSON,因为
JSON.parse
不是一个异步函数,所以我们不必在单独的
处理程序中执行它。

jsonString
从何而来?@theourtheyesry,忘记catch(e){…}