微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Node 中编写同步函数

如何解决如何在 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.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?