如何在nodejs中处理同一个get函数的多个调用?

使用Ajax调用我每10秒钟调用下面的get函数,以便我可以监视一些URL的状态。

app.get('/getUrl', function(req, res) { var response = {}; var keyArr = []; var urlData = []; var responses = []; var dataArr = []; var keyArrLength; //Listing All the URLS db.list(function(err, data) { keyArrLength = data.rows.length; dataArr = data.rows; console.log("keyArrLength" + keyArrLength); pushHost(); }); //Getting the key ie HOSTNAMES function pushHost() { dataArr.forEach(function(arrayItem) { var host = arrayItem.key; keyArr.push(host); console.log("Array of hosts" + keyArr); }); next(0); //Calling the main function } var urlResults = []; var allResponses = []; // Getting the Hostname and URL function next(index) { if (index === keyArrLength) { // No items left res.end(JSON.stringify(allResponses)); return; } else { //Getting one URL at a time db.get(keyArr[index], function(err, data) { currentUrl = data.url; hostname = data._id; var options = { url: "https://" + currentUrl, strictSSL: false, method: 'GET' }; //Requesting data for that one URL request(options, function(error, response, body) { if (!error && response.statusCode == 200) { var response = {}; response.body = JSON.parse(body); response.hostname = hostname; allResponses.push(response); //Pushing the data to final result } else if (error || response.statusCode != 200) { var response = {}; //Appending error results when it enters error handler response.body = { "servicesStatus": [{ "name": "name1", "active": false }, { "name": "name2", "active": false }, { "name": "name3", "active": false }], } response.hostname = hostname; allResponses.push(response); //pushing data } next(index + 1); //Calling recursively till the last URL }); }); }; } }); 

1)在db.list i'm getting the list of all the URL's并获取db.list i'm getting the list of all the URL's长度或数量。

2)在推主机function我推动所有的关键字是这个URL的主机名。 因此,在keyArrLength has the total number of URLS and keyArr has the list of all the hostnames ie keys

3)然后我打电话给next()

4)在next()我正在做每个url的请求调用,并将数据存储为form of object in an array allResponses[]form of object in an array allResponses[]

5)如果它进入error handling程序,我将结果追加到allResponses[]

6)我打电话直到最后一个url分配

  index=0 in the beginning and incrementing in each loop 

7)当我每10秒调用一次该函数时,IT工作正常。

8)但是当我刷新页面,这个getUrl将被调用,并且它将已经执行,因为这个调用每10秒进行一次。 所以他们都碰撞和resullts重复。

我是nodejs的新手。 我不知道我是否做得很好,还是有更好的方法来打这些电话。

我想知道,即使我刷新页面任何次数,我想这个function按顺序执行。 如果最近的通话中断了以前的通话,我需要终止以前的通话并从最新的通话开始。

非常感谢您阅读本文! 请尽可能帮忙! build议如果你知道任何更好的方法来做到这一点。提前感谢。

最后我发现了这个问题。上面的代码只是罚款。 问题是我没有添加var到这个hostname = data._id; 因此它存储了以前的值。 这是问题。