javascript - 了解 JS 事件循环

标签 javascript jquery asp.net

<分区>

我正在尝试理解 js 事件循环。 这是我的 js 代码:

var start = new Date().getTime();
var url = "/WebForm1.aspx/Test1";
$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log('Test1, elapsed: ' + (new Date().getTime() - start) + 'ms');
    },
});

url = "/WebForm1.aspx/Test2";
$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log('Test2, elapsed: ' + (new Date().getTime() - start) + 'ms');
    },
});

url = "/WebForm1.aspx/Test3";
$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log('Test3, elapsed: ' + (new Date().getTime() - start) + 'ms');
    },
});

这是我的服务器端代码:

[WebMethod]
public static void Test1()
{
    System.Threading.Thread.Sleep(1500);
}

[WebMethod]
public static void Test2()
{
    System.Threading.Thread.Sleep(2000);
}

[WebMethod]
public static void Test3()
{
    System.Threading.Thread.Sleep(3000);
}

现在的结果是:

Test1, elapsed: 1542ms
Test3, elapsed: 4578ms
Test2, elapsed: 6636ms

现在我不明白的是,为什么他们不一起执行?是服务器端一次只能处理一个请求,还是跟js事件循环有关?

最佳答案

这个实验表明服务器一个接一个地处理请求,而不是并行处理。 为什么这不是很明显。

服务器可能是单线程的。另一种可能性是请求需要共享(锁定)资源,例如用户 session 或锁定的数据库表。

关于javascript - 了解 JS 事件循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32459862/

相关文章:

c# - 如何在asp :BoundField?中将日期时间更改为本地GMT日期时间

c# - 使用字段掩码并强制光标向左

javascript - Backbone.js 打印 "function String() { [native code] }"而不是模型属性

javascript - 验证隐藏的输入字段

jquery - 检查单击的 href 是否有哈希值,并且不执行任何其他操作转到链接

javascript - 如何像gmail一样实现 "pop down"

javascript - 如何通过 jquery-1.11.0.min 版本隐藏/更改 div 元素内容

asp.net - 重定向主页

javascript - d3js 掩码在条形图上显示点

javascript - 从 e.target.parentNode 获取特定 div 后,我们如何访问它的某些属性/属性