我有以下代码:
app.get('/pull-requests', function (request) {
fetchRepos(fetchPullRequests);
app.on('pull-requests:fetched', function (pullRequestsByRepo) {
var html = "";
_.each(pullRequestsByRepo, function (pullRequests) {
html += 'There is <strong>'+ pullRequests.length +'</strong> pending pull request(s) for <strong>'+ pullRequests[0].title +'</strong>:';
html += '<ul>';
_.each(pullRequests, function (pullRequest) {
html += '<li><em>'+ pullRequest.title +'</em> (<a href="'+ pullRequest.url +'">'+ pullRequest.url +'</a>)</li>';
});
html += '</ul>';
});
response.send(html);
});
});它曾经运作得很好。每秒钟请求都会引发一个错误Can't set headers after they are sent.。
编辑:显示逻辑的更多代码
function fetchRepos (callback) {
_options.path = '/orgs/'+ app.get('org') +'/repos?client_id='+ app.get('client_id') +'&client_secret='+ app.get('client_secret');
// Fetch the list of repos for a given organisation
var request = https.get(_options, function (res) {
data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
var repos = JSON.parse(data);
return callback(repos);
});
});
request.on('error', function (error) {
console.log('Problem with request: '+ e);
});
}
function fetchPullRequests (repos) {
var pullRequests = [];
_.each(repos, function (repo, index) {
_options.path = '/repos/'+ app.get('org') +'/'+ repo.name +'/pulls?client_id='+ app.get('client_id') +'&client_secret='+ app.get('client_secret');
var request = https.get(_options, function (res) {
(function () {
var data = "";
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
data = JSON.parse(data);
if (data.length > 0) {
pullRequests.push(data);
}
if (index == (repos.length - 1)) {
app.emit('pull-requests:fetched', pullRequests);
}
});
})();
});
});
}发布于 2014-03-19 16:29:57
您的问题是,无论何时调用app.on('pull-requests:fetched', …),都会添加一个新的侦听器,这意味着当第二个请求到达时,它将再次触发第一个侦听器。
节点随后会抱怨,因为您尝试对第一个请求进行两次答复。
您可以通过调用app.once来解决当前的问题,这将确保只触发一次,但是如果同时收到两个请求,您仍然会遇到问题。
在这种情况下,正确的模式是向fetchRepos传递一个回调。
https://stackoverflow.com/questions/22511799
复制相似问题