简体   繁体   English

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

[英]node.js + request => node.js + bluebird + request

I'm trying to understand how to write code with promises. 我试图了解如何使用promises编写代码。 Check my code plz. 检查我的代码plz。 This is right? 这是正确的?

Node.js + request: 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);
    }
});

Node.js + bluebird + request: Node.js + bluebird +请求:

request.getAsync(url)
   .spread(function(response, body) {return body;})
   .then(JSON.parse)
   .then(function(json){console.log(json)})
   .catch(function(e){console.error(e)});

How to check response status? 如何查看响应状态? I should use if from first example or something more interesting? 我应该使用if第一个例子还是更有趣的东西?

You can simply check if the response.statusCode is not 200 in the spread handler and throw an Error from that, so that the catch handler will take care of it. 你可以简单地检查response.statusCode不是200的spread处理程序,并抛出一个Error从,使catch处理器将照顾它。 You can implement it like this 你可以像这样实现它

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

And if you notice, we return the parsed JSON from the spread handler, because JSON.parse is not an async function, so we don't have to do it in a separate then handler. 如果你注意到了,我们从返回解析JSON spread处理,因为JSON.parse不是一个异步函数,所以我们没有做,在一个单独的then处理。

One way to check the status code: 检查状态代码的一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM