麻烦从异步调用处理数据

时间:2015-07-01 13:31:57

标签: node.js asynchronous

所以这是我的任务:

  

您必须收集每个提供给您的完整内容   URL和d将其打印到控制台(stdout)。你不需要打印   超出长度,只将数据作为字符串;每个网址一行。抓住了   是你必须按照与URL相同的顺序打印出来   作为命令行参数提供给你。

我这样做:

var http = require('http');
var dataStream = [];
var dataArr = [];
var count = 0;
/*
 Function to print results
 @dataArr - array
*/
function printResults(dataArr) {
  for (var i = 0; i < process.argv.length - 2; i++)
    console.log(dataArr[i]);
}

/*
  Function to get data from http
  @i - int
  Getting command line arguments as parametrs.
*/
function httpGet(i) {
  http.get(process.argv[2 + i], function(res) {

    res.setEncoding('utf8');

    res.on('data', function(data) {
      dataStream.push(data);
    });

    res.on('end', function() {
      dataArr[i] = (dataStream.join(""));
      dataStream = [];
      count++;
      if (count == process.argv.length - 2) {
        printResults(dataArr);
      }
    });

    res.on('error', function(e) {
      console.log("Got error: " + e.message);
    });
  });
}

for (var i = 0; i < process.argv.length - 2; i++) {
  httpGet(i);
}

由于某种原因,有时它会按照预期将数据存储在数组中,但有时它会中断并输出完全无意义的内容。

一些结果示例:

工作时

$ learnyounode verify program.js

Your submission results compared to the expected:

────────────────────────────────────────────────────────────────────────────
────

1.  ACTUAL:    "Shazza got us some trackies when as stands out like dog's ba
lls. Grab us a show pony heaps he hasn't got a lurk. She'll be right rubbish
 mate it'll be budgie smugglers. You little ripper bloke heaps we're going t
op end. He's got a massive bog standard also built like a freckle. "
1.  EXPECTED:  "Shazza got us some trackies when as stands out like dog's ba
lls. Grab us a show pony heaps he hasn't got a lurk. She'll be right rubbish
 mate it'll be budgie smugglers. You little ripper bloke heaps we're going t
op end. He's got a massive bog standard also built like a freckle. "

2.  ACTUAL:    "As dry as a sook and as dry as a cleanskin. As cunning as a
metho where get a dog up ya parma. "
2.  EXPECTED:  "As dry as a sook and as dry as a cleanskin. As cunning as a
metho where get a dog up ya parma. "

3.  ACTUAL:    "Gutful of gyno how come a mokkies. It'll be clacker and buil
t like a holy dooley!. Get a dog up ya boozer heaps come a captain cook. "
3.  EXPECTED:  "Gutful of gyno how come a mokkies. It'll be clacker and buil
t like a holy dooley!. Get a dog up ya boozer heaps come a captain cook. "

4.  ACTUAL:    ""
4.  EXPECTED:  ""

这是一个不工作的例子:

$ learnyounode verify program.js

Your submission results compared to the expected:

────────────────────────────────────────────────────────────────────────────
────

1.  ACTUAL:    "of bogan with it'll be rort. He hasn't got a give it a burl
flamin you little ripper dinky-di. Watch out for the mate's rate to shazza g
ot us some swag. "
1.  EXPECTED:  "He's got a massive op shop to you little ripper corker. Gutf
ul of bogan with it'll be rort. He hasn't got a give it a burl flamin you li
ttle ripper dinky-di. Watch out for the mate's rate to shazza got us some sw
ag. "

2.  ACTUAL:    "You little ripper thongs when as stands out like ropeable. T
rent from punchy boardies bloody as cunning as a brisvegas. "
2.  EXPECTED:  "You little ripper thongs when as stands out like ropeable. T
rent from punchy boardies bloody as cunning as a brisvegas. "

3.  ACTUAL:    "As dry as a uluru when come a scratchy. Flat out like a ute
with get a dog up ya chrissie. As busy as a fair go no worries it'll be fair
 dinkum. She'll be right freo when it'll be cracker. He's Watch got out a fo
r massive the op crook shop my to as you busy little as ripper a corker. bru
mby. Gutful "
3.  EXPECTED:  "As dry as a uluru when come a scratchy. Flat out like a ute
with get a dog up ya chrissie. As busy as a fair go no worries it'll be fair
 dinkum. She'll be right freo when it'll be cracker. Watch out for the crook
 my as busy as a brumby. "

4.  ACTUAL:    ""
4.  EXPECTED:  ""

2 个答案:

答案 0 :(得分:1)

请勿将res.on(“data”)上收到的数据视为数组。相反,将其视为字符串并将其定义为http函数中的变量(而不是全局变量)并执行str += data

或者,您可以查看使用像Async这样的库来管理您需要执行的异步函数的正确排序,因为您需要按顺序执行和返回每个Async。

答案 1 :(得分:0)

所以问题是:

  

您的代码假设3个http响应不会   重叠 - 一个响应的数据事件以前永远不会发生   在上一次回复的结束事件中,情况并非总是如此。一世   建议你在里面移动dataStream变量的定义   你的httpGet函数,这样每个请求/响应都会有它   自己的变量,无论如何都不能相互干扰   定时。

所以我重构了我的解决方案看起来像这样,现在它可以100%的时间工作:

var http = require('http');
var dataArr = [];
var count = 0;
/*
 Function to print results
 @dataArr - array
*/
function printResults(dataArr) {
  for (var i = 0; i < process.argv.length - 2; i++) {
    console.log(dataArr[i].replace('undefined', ''));
  }
}

/*
  Function to get data from http
  @i - int
  Getting command line arguments as parametrs.
*/
function httpGet(i) {
  http.get(process.argv[2 + i], function(res) {

    res.setEncoding('utf8');

    res.on('data', function(data) {
        dataArr[i] += data;
    });

    res.on('end', function() {
      count++;
      if (count == process.argv.length - 2) {
        printResults(dataArr);
      }
    });

    res.on('error', function(e) {
      console.log("Got error: " + e.message);
    });
  });
}

for (var i = 0; i < process.argv.length - 2; i++) {
  httpGet(i);
}

更多信息:https://github.com/nodeschool/discussions/issues/1270