q-io:如何使用Promises读取response.body JSON对象?
我需要从一台服务器到另一台服务器发出一个http请求。
处理这个请求的服务器将返回一个JSON数组对象:
app.get('/array', function (req, res) { console.log('GET request received!'); var response_array = [ { value: 1234 }, { value: 1234 }, { value: 55 } ]; res.send(response_array); });
我正在使用q-io
将http请求发送到GET方法/array
并获取数组:
var _getArray = function(externalUrl) { var request = { method: "GET", url: externalUrl }; return HTTP.request(request) .then(function(response) { // I need to return the Array inside the body (a Promise) to // iterate on it later return response.body.read(); // but .read() returns a Buffer }); }
这两个服务器正常工作,因为请求被正确地发送和接收从一个到另一个,也是响应。
我有的问题是,我没有达到获得JSON数组 – 因为read()
返回一个缓冲区,只是response.body
不返回数组(如文档说,它返回一个可读stream的表示)。 ..我怎样才能妥善处理这个正确的承诺获得arrays?
如果您可以获得响应正文内容的承诺,那么可以通过传递JSON负载来获得JSON负载的承诺。
return HTTP.request(request) .then(function(response) { return response.body.read() }) .then(JSON.parse);
从文档, https://github.com/kriskowal/q-io#body
看来你必须使用forEach
来获取所有项目