我如何一个接一个地执行nodejs HTTP请求?
我有一堆HTTP请求,我需要一个接一个地发送到Web服务。我不想同时运行它们,因为我会因为对服务运行那么多同时查询而遇到麻烦。
我以为我可以通过等待和异步函数来做到这一点,但似乎它仍然没有等待一个请求在另一个之前完成。如果我运行下面的代码,所有50个请求都会被激活,因为我的计算机可以发送它们...
我只是使用承诺错了吗?有一个更好的方法吗?我只是羞于回写编写CURL命令:P。
#!/usr/bin/env node
const [, , ...args] = process.argv
const request = require('request');
const fs = require('fs');
function downloadReport(options){
return new Promise((resolve, reject) => {
console.log("Sending request at " + new Date() );
request(options, function(error,response,body){
if (error) reject(error);
console.log("----------------------------------------------------------------------------------------------------");
console.log("options is " + JSON.stringify (options));
console.log("----------------------------------------------------------------------------------------------------");
console.log("Request Complete at " + new Date() );
resolve(body);
});
});
}//END FUNCTION DOWNLOAD REPORT
async function pullReport(options){
console.log("report pull for " + options.i);
try{
var body = await downloadReport(options);
console.log("Writing out " + options.i + " - report.txt\r\n");
console.log("----------------------------------------------------------------------------------------------------");
fs.writeFile(options.i + " - report.txt", body, function(err) {
if(err) {
return console.log(err);
}
});
}catch(ex){
console.error('ERROR:');
console.error(ex);
}
}//END PULLREPORT FUNCTION
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
const url = ""
for (var i = 1; i<=50;i++){
var options = {
method: 'GET',
url: url,
i:i
};
console.log("***********************************************************************************************");
pullReport(options);
console.log("***********************************************************************************************");
}//END FOR LOOP
回答如下:
看来你只需要在你的循环中使用await pullReport(options);
:
(async function main() {
try {
for (var i = 1; i<=50; i++){
var options = {
method: 'GET',
url: url,
i:i
};
console.log("***********************************************************************************************");
await pullReport(options);
console.log("***********************************************************************************************");
}
} catch (err) {
console.error(err);
}
})();