根据评论/答案,请参阅问题底部的更新:这个问题实际上是关于不执行回调的隐藏线程的可能性。
我有一个关于节点请求模块的潜在神秘场景的问题,其中:
一个完整的 HTTP 请求在网络上构建和执行(需要很多毫秒甚至几秒)
...在本地机器上运行时执行单个函数之前(通常以纳秒为单位?) - 请参阅下文了解详细信息
我发布此内容主要是为了确保我不会误解有关 Node / JS / Request 模块代码的内容。
从请求模块中的示例(请参阅该部分中的第二个示例),是这样的:
// Copied-and-pasted from the second example in the
// Node Request library documentation, here:
// https://www.npmjs.com/package/request#examples
// ... My ARCANE SCENARIO is injected in the middle
var request = require('request')
request(
{ method: 'GET'
, uri: 'http://www.google.com'
, gzip: true
}
, function (error, response, body) {
// body is the decompressed response body
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
)
// **************************************************** //
// Is the following scenario possible?
//
// <-- HANG HANG HANG HANG HANG HANG HANG HANG HANG -->
//
// Let us pretend that the current thread HANGS here,
// but that the request had time to be sent,
// and the response is pending being received by the thread
//
// <-- HANG HANG HANG HANG HANG HANG HANG HANG HANG -->
// **************************************************** //
.on('data', function(data) {
// decompressed data as it is received
console.log('decoded chunk: ' + data)
})
.on('response', function(response) {
// unmodified http.IncomingMessage object
response.on('data', function(data) {
// compressed data as it is received
console.log('received ' + data.length + ' bytes of compressed data')
})
})
我在代码片段中指出了我的神秘场景。
假设 Node 进程在指示点挂起,但 Node 内部(在隐藏线程中,对 Javascript 不可见,因此不调用任何回调)能够构造请求,并通过网络发送;假设挂起一直持续到收到响应(比如说,分成两个块)并等待节点处理。(这种情况肯定是神秘的,我什至不确定理论上是否可行。)
然后假设挂起结束,上面的Node线程被唤醒。此外,假设(以某种方式)Node 能够一直处理响应,直到执行上述代码中的回调函数(但又没有移过原始代码路径中代码中的“挂起”点) ,如果这在理论上是可能的)。
上述神秘的场景在理论上是可能的吗?'data'
如果是这样,在对象上安排事件之前,是否会通过网络接收数据包并进行组合,准备好传递给回调函数?在这种情况下,如果可能的话,我想这个'data'
事件会被错过。
同样,我知道这是一个神秘的场景——考虑到所涉及的内部机制和编码,这在理论上可能是不可能的。
那是我的问题 - 上述神秘的场景,其极不可能的比赛条件,但理论上是可能的吗?
我问只是为了确保我没有遗漏一些关键点。谢谢。
更新:来自评论和答案:我现在已经澄清了我的问题。“神秘场景”需要有一个隐藏线程(因此不能执行任何用户代码,包括回调)来构造请求,通过网络发送它并接收响应 - 没有任何回调触发,包括'data'
回调 - 并在回调准备好被调用时停止'response'
,等待(单个)可见 JS 线程唤醒。