NodeJS Semaphore 无限加载页面
我正在编写一个程序,当客户端加入“/json”时,它会为您提供一个 json。我想用一个信号量来调整这个,每次有 1 个客户端请求资源,如果它发生了变化,那么它就会给你。我在 npm 中使用一个名为“semaphore”的包(https://www.npmjs.com/package /信号量)。
kasRouter.get(path + '/json',(req,res)=>{
sem.take(async () => {
let toggle2 = await utils.getToggleKas()
console.log(req)
if(toggle2 != toggle){
sem.leave()
toggle = toggle2
console.log(toggle)
res.json({
'kas':toggle
})
}
})
})
如您所见,当客户端加入路径时,我使用 sem.take() 函数让客户端等待离开它。切换和切换2基本上是2个变量,它们在json(在数据库中)中采用布尔值。当主路由启动时,第一个切换获取布尔值,当客户端加入 json 路径时,等待切换更改。此代码中的问题是客户端无休止地尝试在页面中进行连接,但服务器却没有响应。
i'm writing a program that when a client joins to "/json", it gives you a json. I want to adjust this with a semaphore where 1 client per time requests the resource and if it's changed, then it gives to you. I'm using a package in npm called "semaphore" (https://www.npmjs.com/package/semaphore).
kasRouter.get(path + '/json',(req,res)=>{
sem.take(async () => {
let toggle2 = await utils.getToggleKas()
console.log(req)
if(toggle2 != toggle){
sem.leave()
toggle = toggle2
console.log(toggle)
res.json({
'kas':toggle
})
}
})
})
as you can see, when the client joins in the path, i use sem.take() function to let the client wait for leaving it. toggle and toggle2 are basically 2 vars that take a boolean in the json (in a database). When the main route starts the first toggle gets the boolean and when the client joins in the json path waits for toggle chages. The problem in this code is that client tries infinit endlessly to connect in the page but without a response from the server.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,你似乎错过了一些东西。也就是说,您不会调用
res.end
,并且仅当await utils.getToggleKas()
的结果发生更改时才会调用sem.leave
请参阅如果下面的代码片段有帮助
Ok, you seem to be missing some things. Namely, you don't call
res.end
andsem.leave
is only called if the result fromawait utils.getToggleKas()
changesSee if the code snippet below helps