如何计算回调?

How to count callbacks?

我尝试从 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);
});

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

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

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

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

我的解决方案,简单明了

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

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

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

在您的代码中检查回调函数中的结束值 (ended===3)。我使用类似的 approach.Note 解决了这个问题,我对所有三个 url 使用了一个回调函数

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

我使用更少代码的工作解决方案:

const http = require('http')

const [, , URL_1, URL_2, URL_3] = process.argv

const printData = (URL, cb) =>
    () => http.get(URL, res => {
        let data = ''
        res.on('data', chunk => data += chunk.toString())
        res.on('end', () => {
            console.log(data)
            cb()
        })
    })

printData(URL_1, printData(URL_2, printData(URL_3, null)))()