问题描述
https://github.com/nodejs/node/issues/36978
Source Code - https://github.com/raj-here/leaning-node-2
我想要的是,当多个请求试图访问同一个函数时,它应该被锁定一个,直到该函数内没有处理数据。
当我一次发送一个请求时它工作正常,但是当用户一次发送多个请求时,逻辑会中断(这应该是不言自明的!当您查看下面的代码时)。
>我曾在 Java 中做过类似的事情并且确实有效。
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
节点 API 代码:
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);
})
}
客户代码:
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));
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)