如何在 Node 中编写同步函数

问题描述

谁能帮我在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 (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...