首页 > 解决方案 > 快速服务器并发

问题描述

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 秒的等待时间。据我所知,如果客户来了,它就会等待。不应影响另一个客户。但在我的代码中,第二个客户必须等到第一个客户得到满足。

标签: javascriptnode.jsexpress

解决方案


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')
}

推荐阅读