node.js + request => node.js + bluebird + request

5

我将尝试解释如何使用 Promise 编写代码。

请检查我的代码是否正确。

Node.js + request:

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

Node.js + bluebird + request:

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语句还是其他更有趣的方法?

2
jsonString 是从哪里来的? - thefourtheye
@thefourtheye 抱歉,忘记了 catch(e) {...} 的部分。 - Sergey P.
2个回答

11

您可以在spread处理程序中检查response.statusCode是否不为200,如果是,则抛出一个Error,以便catch处理程序可以处理它。您可以按照以下方式实现它:

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 不是异步函数,所以我们不必在一个单独的 then 处理程序中执行它。


0

检查状态码的一种方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接