gpt4 book ai didi

Node.JS - 使用异步函数处理传入请求

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:38 26 4
gpt4 key购买 nike

据我了解,Node.js 是单线程的,一次处理每个请求。但是,当进行异步调用时,它应该能够在尚未调用回调的情况下处理新请求。

那么,当我同时向以下服务器实现发出 3 个请求时,为什么它等待第一个响应 10 秒,然后等待第二个响应 20 秒,第三个响应等待 30 秒......?

var express = require('express');    
var app = express();
app.get('*', function(req, res) {
setTimeout(function(){
res.end('done')
},10000)
});
app.listen(8000);

最佳答案

您应该使用另一个 node.js 脚本对其进行测试,而不是使用浏览器进行检查...例如,使用此脚本:

var http = require('http');

function test(timestamp) {
http.get('http://127.0.0.1:8000',function(res) {
console.log(new Date() - timestamp);
});
}


for (var i = 0 ; i < 5 ; i++) {
test(new Date().getTime());
}

我得到以下结果(使用您的代码作为http服务器):

> node test.js
10032
10029
10029
10029
10030

看来问题不在于您的node.js 代码。

关于Node.JS - 使用异步函数处理传入请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28250612/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com