我正在尝试编写一个从COVID-19 API中提取数据的函数。这是我的功能:
function covidcases(){
var http = require('follow-redirects').http;
var fs = require('fs');
var options = {
'method': 'GET',
'hostname': 'covidtracking.com',
'path': '/api/us',
'headers': {
},
'maxRedirects': 20
};
var req = http.request(options, function (res) {
return new Promise((resolve, reject) => {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function (chunk) {
var body = Buffer.concat(chunks);
console.log("From the console.log: "+body.toString());
resolve(body.toString());
});
res.on("error", function (error) {
reject(error);
});
})
});
req.end();
}
module.exports = {covidcases}
console.log(covidcases())
在Visual Studio代码中运行时,结果如下:
undefined
From The console.log: [{"date":20201011,"states":56,"positive":7727630,"negative":102250976,"pending":11261,"hospitalizedCurrently":34028,"hospitalizedCumulative":423058,"inIcuCurrently":6583,"inIcuCumulative":21553,"onVentilatorCurrently":1614,"onVentilatorCumulative":2454,"recovered":3075077,"dateChecked":"2020-10-11T00:00:00Z","death":206597,"hospitalized":423058,"totalTestResults":115424481,"lastModified":"2020-10-11T00:00:00Z","total":0,"posNeg":0,"deathIncrease":464,"hospitalizedIncrease":999,"negativeIncrease":800029,"positiveIncrease":46776,"totalTestResultsIncrease":943645,"hash":"deda38c4ef4e1ba880c187cc8f0b1e67f7822f36"}]
我的猜测是该函数没有等待Buffer.concat(chunks)完成。我该如何解决?