Node.js   发布时间:2022-04-24  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了并发 – Node.js调试跟踪似乎意味着多个执行线程 – 如何正确解释这个?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在使用Node.js时遇到了一些麻烦,我认为问题可能是我误解了Node.js的并发方法.这是我编写的服务器的精简示例.这个想法是服务器将用于自动化测试:它保留一个预期的“配置”列表,并将它们与客户端发送的“配置”进行比较.

//expectedConfigurations gets initialized up here

var server = http.createServer(function(request,responsE) {
    switch (url.pathName) {
        case "/check-configuration":
            jsonData = "";
            request.on("data",function(data) {
                return jsonData += data;
            });

            request.on("end",function() {
                var configuration,errMsg,expectedConfiguration;

                console.log("finished reading json data",jsonData);
                expectedConfiguration = expectedConfigurations.shift();
                console.log("Expected configuration",expectedConfiguration);
                configuration = new Set(JSON.parse(jsonData));
                if (expectedConfiguration.equals(configuration)) {
                    response.writeHead(200,{"Content-Type": "text/plain"});
                    response.write("Matched expected configuration.");
                    return response.end();
                } else {
                    response.writeHead(500,{
                        "Content-Type": "text/plain"
                        });
                    errMsg = "Did not match expected configuration. Received: " + (JSON.Stringify(configuration)) + ". Expected:" + (JSON.Stringify(expectedConfiguration)) + ".";
                    response.write(errMsg);
                    response.end();
                    console.error(errMsg);
                    results.testsFailed.push(currentTest);
                    return transitionToBeforeSendingTestState();
                }

            })
    }
})

我的理解是Node.js是单线程的,因此然它可以产生可以异步处理的多个任务,但是一次只有一个执行线程将进入在Node.js下运行的JavaScript代码.不幸的是,我从服务器收到的调试输出似乎无视这个假设:

received request for /check-configuration
finished reading json data [ "a" ]
Expected configuration [ "a" ]
received request for /check-configuration
Did not match expected configuration. Received: [ "a" ]. Expected: [ "c" ].

我读这个如下:

>服务器收到请求.它开始异步读取请求数据.
>服务器完成读取请求数据,通过移动它来改变expectedConfigurations,并将结果分配给expectedConfiguration [‘a’]
>然后线程被服务器的新请求打断!这就是我对Node.js下单线程执行JavaScript内容的期望似乎打破了.
>最后,与第一个请求关联的原始执行线程恢复.将预期的配置与接收的实际配置进行比较,但现在,不是像在步骤2中那样具有值[‘a’],而是具有值[“c”].

似乎我必须正确地解释这个,因为它违背了我对Node.js的单线程执行模型的理解,但是现在我无法看到如何解释这个问题.我很感激任何人都可以提供任何指导.

解决方法

尝试使用COnsole.error而不是console.log到处重复相同的测试. 据我所知,console.log是非阻塞的(数据在调用时被缓冲并在稍后的某个时刻被写入stdout)并且console.error被阻塞.

大佬总结

以上是大佬教程为你收集整理的并发 – Node.js调试跟踪似乎意味着多个执行线程 – 如何正确解释这个?全部内容,希望文章能够帮你解决并发 – Node.js调试跟踪似乎意味着多个执行线程 – 如何正确解释这个?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。