根据评论/答案,请参阅问题底部的更新:这个问题实际上是关于可能性的hidden不执行回调的线程。
我有一个关于潜在的神秘场景的问题,涉及节点请求模块 https://www.npmjs.com/package/request其中:
我主要将其发布为完整性检查只是为了确保我没有误解有关 Node / JS / Request 模块代码的内容。
来自请求模块中的示例 https://www.npmjs.com/package/request#examples(请参阅该部分的第二个示例)是这样的:
// 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 在内部(在hidden线程,对 Javascript 不可见,因此不会调用any回调)能够构建请求并通过网络发送;假设挂起一直持续到收到响应(例如,分成两个块)并等待 Node 处理。 (这种情况肯定是神秘的,我什至不确定理论上是否可能。)
然后假设挂起结束,上面的 Node 线程被唤醒。此外,假设(以某种方式)Node 能够一直处理响应,直到执行上面代码中的回调函数(但又没有越过原始代码路径中代码中的“挂起”点) ,如果这在理论上是可能的)。
上述神秘的场景理论上可能吗?如果是这样,在执行之前,数据包是否不会通过网络接收并组合起来,准备传递给回调函数'data'
事件已安排在对象上?在这种情况下,如果可能的话,我想'data'
事件将被错过。
再次,我知道这是一个神秘的场景 - 考虑到所涉及的内部机制和编码,也许它在理论上是不可能的。
这就是我的问题 - 上述神秘的场景及其极不可能的竞争条件,在理论上是否可能?
我问这个问题只是为了确保我没有遗漏一些关键点。谢谢。
UPDATE:来自评论和回答:我现在已经澄清了我的问题。 “神秘场景”需要有一个隐藏线程(因此无法执行任何用户代码,包括回调)来构造请求,通过网络发送请求,并接收响应 - 没有任何回调可以触发,包括'data'
回调 - 并在该点停止'response'
回调已准备好被调用,等待(单个)可见 JS 线程唤醒。