我必须提出一个API请求,然后再从获取的数据中获取一个ID,并将其放入另一个API请求中。这不是我的API设计模式,而是它的本质。
我的问题是,当发送JSON响应时,在所有请求完成之前就已经发送了响应。现在,我尝试使用计数器来检查是否已发送所有请求,但发送失败。我将告诉您问题出在哪里:
这是我检查柜台的地方:
if ((counter === counterSum)) {
res.send(projects);
}
问题是,此代码在我的所有计数器都可以“计数”之前运行。
例如,在这一点上,如果我记录计数器,它会达到约22而不是26。由于计数器在我的计数器有机会递增之前已经记录,所以我经常看到该计数器记录了5次左右相同的次数
我现在已经在进行这几个小时了,所以如果有人在Node.js领域内有一个主意,那就太好了。
我将添加一些非常简化的代码,显示我必须经历的所有请求阶段以及进行最终日志检查的位置:
let departmentProcesses = JSON.parse('[' + processes + ']');
Object.keys(departmentProcesses).forEach(function (key) {
console.log('The process' + departmentProcesses[key]);
let val = departmentProcesses[key];
let id = val.id;
let proccessURL = //url with + id
// Get all instances by project id
request({url: processURL},
function (error, response, body) {
//Convert the XML into JSON
parseString(response.body, function (err, result) {
departmentData = JSON.stringify(result);
});
let instanceData = (JSON.parse(departmentData)).feed.entry;
// Pushes to an array so I can sum up all the iterations
counters.push(instanceData.length);
Object.keys(instanceData).forEach(function (key) {
let val = instanceData[key];
let processId = val.id[0];
let nextURL = //url with + id";
request({url: nextURL},
function (error, response, body) {
//Convert the XML into JSON
parseString(response.body, function (err, result) {
departmentData = JSON.stringify(result);
});
let instanceData = (JSON.parse(departmentData)).feed.entry;
let val = instanceData[0].id[0];
let todoLink = //url with + id";
request({url: todoLink},
function (error, response, body, callback) {
//Convert the XML into JSON
parseString(response.body, function (err, result) {
departmentData = JSON.stringify(result);
});
let instanceEntry = (JSON.parse(departmentData)).feed.entry;
if (typeof instanceEntry !== 'undefined' && instanceEntry) {
let finalLink = //url with + id";
request({url: finalLink},
function (error, response, body) {
//Convert the XML into JSON
parseString(response.body, function (err, result) {
departmentData = JSON.stringify(result);
});
let instanceEntry = (JSON.parse(departmentData)).feed.entry;
if (typeof instanceEntry !== 'undefined' && instanceEntry) {
upNext = {
// some data
};
let data = {
// some data
}
processInstances.push(data);
counter++;
}
});
}
else {
upNext = 'null';
let data = {
// some data
}
counter++;
}
console.log(counter);
let counterSum = counters.reduce(function (a, b) {
return a + b;
}, 0);
if ((counter === counterSum)) {
res.send(projects);
}
});
});
});
});
let data = {
processName: processName,
id: id,
instances: processInstances
};
projects.push(data);
});