如何计算回调?

时间:2015-12-18 09:37:07

标签: node.js asynccallback

我尝试从3个来源收集数据但这些是异步的。因此我试图计算回调。这是我为此目的编写的代码。

var http = require('http');
var data_str1 = '';
var data_str2 = '';
var data_str3 = '';
var ended = 0;
function callback1(response){
    response.on('end', function(){ended++;});
    response.on('data', function(data){
        data_str1 += data;
    });
}

function callback2(response){
    response.on('end', function(){ended++;});
    response.on('data', function(data){
        data_str2 += data;
    });
}

function callback3(response){
    response.on('end', function(){ended++;});
    response.on('data', function(data){
        data_str3 += data;
    });
}

http.get(process.argv[2], function(response){
    callback1(response);
    if (ended == 3) console.log(data_str1);
});

http.get(process.argv[3], function(response){
    callback2(response);
    if (ended == 3) console.log(data_str2);
});

http.get(process.argv[4], function(response){
    callback3(response);
    if (ended == 3) console.log(data_str3);
});

你能告诉我这段代码有什么问题吗?

6 个答案:

答案 0 :(得分:6)

这是我的解决方案。我已经过测试并且有效。

var http = require('http');
var concat = require('concat-stream');

var urls = [];
var responses = [];
var count = 0;

for (var i = 2; i < process.argv.length; i++) {
  urls.push(process.argv[i]);
}

function readResponse(index) {
  http.get(urls[index], function(response) {
    response.pipe(concat(function(data) {
      responses[index] = data.toString();
      count++;

      if (count == 3) {
        responses.forEach(function(response) {console.log(response);});
      }
    }));
  });
}

for (var i = 0; i < urls.length; i++) {
  readResponse(i);
}

答案 1 :(得分:1)

const http = require('http');
const bl = require('bl');
const results = [];
let count = 0;
function printResults () {
  for (let i = 0; i < 3; i++) {
    console.log(results[i])
  }
}

function httpGet (index) {
  http.get(process.argv[2 + index], function (response) {
    response.pipe(bl(function (err, data) {
      if (err) {
        return console.error(err)
      }

      results[index] = data.toString()
      count++

      if (count === 3) {
        printResults()
      }
    }))
  })
}

for (let i = 0; i < 3; i++) {
  httpGet(i)
}

答案 2 :(得分:0)

这里的问题是 if (ended == 3) console.log(data_str2); 将在callback2(response);之后运行 它不等待response.on('end', function(){ended++;});

答案 3 :(得分:0)

我的解决方案,简单明了

const http = require('http')
const bl = require('bl')
const results = []
let count = 0

function printResults () {
  for (let i = 0; i < 3; i++) {
    console.log(results[i])
  }
}

function httpGet (index) {
  http.get(process.argv[2 + index], function (response) {
    response.pipe(bl(function (err, data) {
      if (err) {
        return console.error(err)
      }

      results[index] = data.toString()
      count++

      if (count === 3) {
        printResults()
      }
    }))
  })
}

for (let i = 0; i < 3; i++) {
  httpGet(i)
}

答案 4 :(得分:0)

在您的代码中,检查回调函数中的结束值(ended === 3)。我使用类似的方法解决了这个问题。请注意,我对所有三个网址都使用了一个回调函数

const http = require("http");

let url1 = process.argv[2];
let url2 = process.argv[3];
let url3 = process.argv[4];
let str1 = "";
let str2 = "";
let str3 = "";
let end = 0;

function cb(response, str) {
  response.on("data", data => {
    if (str === "str1") str1 += data;
    if (str === "str2") str2 += data;
    if (str === "str3") str3 += data;
  });
  response.on("end", () => {
    end++;
    if (end === 3) {
      console.log(`${str1}\n${str2}\n${str3}`);
    }
  });
}

http.get(url1, response => {
  cb(response, "str1");
});

http.get(url2, response => {
  cb(response, "str2");
});

http.get(url3, response => {
  cb(response, "str3");
});

答案 5 :(得分:-2)

我知道这是一个古老的问题,但是我只是想用另一种方法来分享我的丑陋解决方案。

const http = require('http');

let data1 = '';
let data2 = '';
let data3 = '';

http.get(process.argv[2], (res) => {
    res.on('data', (data) => {
        data1 += data;
    })
    res.on('end', () => {
        http.get(process.argv[3], (res) => {
            res.on('data', (data) => {
                data2 += data;
            })
            res.on('end', () => {
                http.get(process.argv[4], (res) => {
                    res.on('data', (data) => {
                        data3 += data;
                    })
                    res.on('end', () => {
                        console.log(data1); console.log(data2); console.log(data3);
                    })
                })
            })
        })
    })
})