나는 익스프레스 서버에 다음 코드를 가지고 있습니다 (간단히하기 위해 줄였습니다). 나는 세 가지 다른 편안한 종말점에서 내가 추가/수정/읽는 공통 대상을 가지고있다. nodejs의 모든 HTTP 요청이 비동기 적이기 때문에 동시에 넣고 가져올 수 있습니다. . 따라서 PUT이 발생했지만 상태가 이 아니라고 말하면이 업데이트됩니다. GET이 약간 부실한 응답을받을 수 있습니까?아래에 경쟁 조건이 있습니까?
내가 이해하고있는 바에 따르면 테스트 결과 경쟁 조건이 없다는 것을 보여줍니다. results
개체를 업데이트하는 것은 동기 작업이므로 모든 비동기 작업이이를 기다려야합니다. 이것이 옳은지 아닌지 더 나은 설명을 누군가 도울 수 있습니까?
var obj = {};
const exec = require('child_process').exec;
app.post('/foo', (req, res) => {
var result = {};
result.id = generateSomeRandomId();
result.failed = 0;
result.status = 'running'
//execute some command and update result
const child = exec('some command');
child.stdout.on('data', (data) => {
//some logic
});
child.stderr.on('data', (data) => {
result.failed = result.failed + 1;
});
child.on('close', (code, signal) => {
if (signal !== null && signal !== undefined) {
result.status = 'cancelled';
} else {
result.status = 'completed';
result.runtime = calculateRunTime();
}
});
result.pid = child.pid;
obj[result.id] = result;
res.send(result);
}
app.put('/foo/:id', (req, res) => {
var result = obj[req.params.id];
if (result.status === 'running' && result.pid !== undefined) {
kill(result.pid, 'SIGKILL');
result.status = 'cancelled';
result.runtime = calculateRunTime();
}
res.send(result);
}
app.get('/foo/:id', (req, res) => {
var result = obj[req.params.id];
res.send(result);
}
당신은'app.post ('/ foo'')에 대해 이야기하고 있습니까? "race"는 없지만 비동기 부분이 실행되기 전에'res.post (result);' 당신이''어떤 명령을 실행하고 결과를 갱신하고''result.pid = child ''사이에 무엇을 하든지간에.pid;는'res.send (result);에서 보낸 내용에 아무런 영향을주지 않을 것입니다. –
또한'result.failed = result.failed + 1;'은'results.failed'가'undefined'이거나, 오류가 있으면'result.failed === NaN' –
@ JaromandaX 예 그 부분을 얻습니다. * post *의 모든 비동기 작업은 모든 동기화 작업이 완료 될 때까지 대기합니다. 내 질문은 대부분 동시 PUT 및 GET 요청에있었습니다. 거기에 경쟁 조건이 있겠습니까? 그리고 당신은 결과에 대해 옳았습니다. NaN 부분을 무시하고 간단하게 초기화를 생략했습니다. 그것을 다시 추가 할 것입니다. – Manali