javascript - 快速服务器并发
问题描述
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send("helo")
});
app.post('/', (req, res) => {
console.log('served');
name(res);
});
async function name(res) {
console.log('waiting')
var waitTill = new Date(new Date().getTime() + 10 * 1000);
while(waitTill > new Date()){}
res.send('ok');
console.log('out of waiting')
}
app.listen(3000, () => console.log('Example app listening on port 3000!'))
简单地说:服务器没有异步行为
说明:这是代码,现在 name 函数有 10 秒的等待时间。据我所知,如果客户来了,它就会等待。不应影响另一个客户。但在我的代码中,第二个客户必须等到第一个客户得到满足。
解决方案
async
函数不是这样工作的。他们需要承诺才能正常工作。同步代码(如痛苦的while(waitTill > new Date())
)仍然是同步的。在 Node 中,实际上很难阻止事件循环而不做一些疯狂的事情,比如长时间运行的while
循环。几乎所有需要时间的事情都被设计成异步的,所以你一般不会遇到这个问题。
要使用async
函数,您需要返回一个承诺的东西。例如,如果我们制作了一个使用setTimeout
包装在 Promise 中的等待版本,那么您不应该遇到事件循环阻塞的问题。
// a more realistic function that takes `time` ms
const wait = time => new Promise(resolve => setTimeout(resolve, time))
app.post('/', (req, res) => {
console.log('served');
name(res);
});
async function name(res) {
console.log('waiting')
await wait(10 * 1000) // await expects wait to return a promise
res.send('ok'); // will send 10 seconds later without blocking the thread
console.log('out of waiting')
}
推荐阅读
- jquery - 在汉堡菜单上单击太快会反转 fadeToggle 效果
- python-3.x - 如何在 python 中使用 Simple ITK 仅更改 Dicom 文件的数组
- javascript - JS HTTP 发布 YAML
- excel - 如何索引匹配唯一值?
- javascript - 如何为可溢出的 div 中始终可见的 thead 和 tbody 添加边框
- javascript - Flutter Web:FCM 无法注册 Service Worker
- git - 我们什么时候需要在 git 中使用 --track 命令
- java - 将 QueryDSl 与 Spring Boot App 集成时出现空指针异常
- git - 如何隔离git子模块的日志
- android - 同一个TextView中的多个id