Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

Node.js中如何循环发送请求?

如题,现在需要向某一个接口持续不断发送请求,使用的是request库,代码如下:

var request = require('request');
var options = {
 'method': 'POST',
 'url': 'https://puzzle.gztime.cc/api/live/uploadlikes',
 'headers':?{
 'Cookie': '**************'
 },
 formData:?{
 'append': '-5000000'
 }
};
exports.uploadlikes=function (){
 request.post(options, function (error, response)?{
 if (error) throw new Error(error);
 console.log(response.body);
 });
}

以上为post.js

var post=require('./post')
while(true){
    post.uploadlikes()
}

以上为main.js
程序执行之后,控制台就没有输出,debug看response的回调函数也一直没有执行,内存持续飙高,求node循环发请求的正确姿势,谢谢大佬们


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

用死循环会阻塞主线程,让事件回调没法执行。将请求发送加入node任务队列,让node事件循环机制帮你发起不断请求,这样请求事件回调函数才有机会执行。

var post=require('./post')
setInterval(post.uploadlikes)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...