简体   繁体   English

highland.js获取json数组并在值流中进行转换

[英]highland.js fetch json array and transform in stream of values

I am trying to fetch a JSON array form an external API and then emit one element of the array at the time. 我正在尝试从外部API获取JSON数组,然后一次发出该数组的一个元素。 However my implementation seems to be failing somewhere, I am getting errors instead of array 但是我的实现似乎在某处失败,我收到错误而不是数组

'use strict';

const request = require('request-promise'),
    H = require('highland');

H(request('http://jsonplaceholder.typicode.com/users'))
  .map(x => x.toString('utf8'))
  .tap((data) => {
      let acc = [];

      data = JSON.parse(data);
      data.forEach((entry) => {
          acc.push(entry);
      });
      return H(acc);
  })
  .each(user => console.log(user.id))// would expect that this logs 1,2,3,4
  .done(data => {
    console.log(data)
});

You're probably getting chunks of data rather than the full response meaning JSON.parse is attempting to parse incomplete JSON. 您可能会得到大量数据,而不是完整的响应,这意味着JSON.parse试图解析不完整的JSON。 Perhaps try something like this? 也许尝试这样的事情?

H(request('http://jsonplaceholder.typicode.com/users'))
  .collect()
  .map(Buffer.concat)
  .flatMap(x => JSON.parse(x.toString('utf8')))
  .each(user => console.log(user.id))
  .done(data => console.log('DONE'));

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

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