sync functions not working
Can someone please help me to write a synchronized function in Node. It is working fine when I'm sending one request at a time, But when users sends multiple request at a time, logics gonna break (It should be self-explanatory! when you will look at below code).
I'd did similar kind of things in Java and it does work.
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
Node API Code:
app.get('/test', async function (req: Request, res: Response) {
await updateData(parseInt(req.query['index'] as string));
res.send('Hello World ' + req.query['index']);
});
let currentVersion: number = 0;
const timer = 20;
const updateData = async (index: number): Promise<void> => {
const currentVersion = await getCurrentVersion();
const latestVersion = currentVersion + 1;
const s3FileName = "file_" + latestVersion + ".pdf";
const seResult = await uploadFileToS3(currentVersion, s3FileName);
console.log("S3 Result", seResult)
setCurrentVersion(latestVersion);
console.log("RequestNumber: ", index, ", LastVersion: ", currentVersion, ", LatestVersion: ", latestVersion);
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
}
const getCurrentVersion = async (): Promise<number> => {
return currentVersion;
}
const setCurrentVersion = async (version: number): Promise<void> => {
currentVersion = version;
}
const uploadFileToS3 = async (currentVersion: number, s3Filename: string): Promise<string> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(s3Filename);
}, (timer - currentVersion) * 1000);
})
}
Client Code:
for (let index = 0; index < 20; index++) {
const url = "http://localhost:8081/test";
fetch(url + `?index=${index}`)
.then(x => x.text())
.then(y => console.log(`${index} ` + y));
}
The problem here is probably that you await the result before updating your version. Therefore multiple requests could end up using the same version. Move your setCurrentVersion(latestVersion) above the await and it should work like you expect it to.
Furthermore async functions have nothing to do with java synchronized methods
It seems there has been no activity on this issue for a while, and it is being closed in 30 days. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.
It seems there has been no activity on this issue for a while, and it is being closed. If you believe this issue should remain open, please leave a comment. If you need further assistance or have questions, you can also search for similar issues on Stack Overflow. Make sure to look at the README file for the most updated links.