我使用 node.js 制作了一个 REST API 服务,它运行良好,直到我在浏览器中打开几个选项卡并(几乎)同时发出几个请求。发送请求的最后一个选项卡获得响应,另一个挂起。
基本上我有一个名为“服务”的模块,它可以完成所有工作:
var service = require('./service');
var server = http.createServer(function(req, res) {
...
var serviceResult = service.runService(parsedURL.query.username, parsedURL.query.api_key);
res.writeHead(200, {'content-type': 'application/json', 'connection' : 'keep-alive' });
service.ready = function(serviceResult) {
var serviceResultJSON = JSON.stringify(serviceResult);
res.writeHead(200, {'content-type': 'application/json', 'connection' : 'close' });
res.end(serviceResultJSON);
}
}
从我调用的服务模块:
service.ready(result);
...只要结果准备好,简而言之就是我的服务器。那么我能做些什么来解决这个问题呢?
编辑:
这是我的 service.js 模块的样子(在建议的更改之后):
// PUBLIC
exports.runService = function(username, apiKey, callback) {
_.username = username;
_.apiKey = apiKey;
init();
userManager.setLastServiceGlobal(function() {
// This call triggers the whole cycle. Below is snapshotManager.createdSnapshot(), which gets executed from within snapshotManager and the cycle moves on until apiManager.ready() gets called from within api-manager.js
snapshotManager.createSnapshot(false);
});
// This is the last .ready() function that gets executed when all other modules have finished their job.
apiManager.ready = function() {
console.log('API Manager ready.');
userManager.updateLastService();
callback(null, serviceResult);
}
}
// PRIVATE
var userManager = require('./user-manager'),
productManager = require('./product-manager'),
commentsManager = require('./comments-manager'),
apiManager = require('./api-manager'),
milestonesManager = require('./milestones-manager'),
statisticsManager = require('./statistics-manager'),
snapshotManager = require('./snapshot-manager'),
serviceResult;
...
snapshotManager.createdSnapshot = function() {
userManager.refreshUserData();
}
snapshotManager.createdNewSnapshot = function() {
milestonesManager.generateMilestones();
}
userManager.refreshedUserData = function() {
userManager.isTimeForPortfolioParse();
}
...
userManager.ready = function() {
console.log('User Manager ready.');
userManagerReady = true;
isDataFetchingOver();
}
productManager.ready = function() {
console.log('Product Manager ready.');
productManagerReady = true;
isDataFetchingOver();
}
commentsManager.ready = function() {
console.log('Comments Manager ready.');
commentsManagerReady = true;
isDataFetchingOver();
}
在这种情况下,模块就像“server.js”文件中的“服务”模块一样被覆盖,对吗?我猜我需要在任何地方实现回调而不是 .ready() 函数,对吗?