如何解决如何在 Node 中编写同步函数
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 举报,一经查实,本站将立刻删除。