我遇到了a presentation(幻灯片50-51),其中作者举例说明了如何批量节点中10000个相同文件读取的回调。
// Batching wrapper around the real FS.readFile
var requestBatches = {};
function batchingReadFile(filename, callback) {
// First check to see if there is already a batch
if (requestBatches.hasOwnProperty(filename)) {
requestBatches[filename].push(callback);
return;
}
// Otherwise start a new one and make a real request
var batch = requestBatches[filename] = [callback];
FS.readFile(filename, onRealRead);
// Flush out the batch on complete
function onRealRead() {
delete requestBatches[filename];
for (var i = 0, l = batch.length; i < l; i++) {
batch[i].apply(null, arguments);
}
}
}
// Request the same resource 10,000 times at once
for (var i = 0; i < 10000; i++) {
batchingReadFile(__filename, onRead);
}
function onRead(err, file) {
if (err) throw err;
}
作为一个新手节点开发人员,在这个例子中有一件事我只是不知道如何将变量callbacks
设置为只包含一个回调函数(var callbacks = requestBatches[filename] = [callback];
)的数组,但是怎么能它在onRead
函数中包含10000个回调函数?
我得到onRead
函数放在事件队列中,直到batchingReadFile
函数被调用10000次才被调用,但是,其他回调函数如何结束在callbacks
?
我错过了一些非常明显的东西吗?如果是这样,请保持温和,并为我指出。
答案 0 :(得分:0)
您似乎错过了代码;
if (filename in requestBatches) {
requestBatches[filename].push(callback);
return;
}
...这确保了对batchedReadFile
的连续调用,使用相同的文件名,将其回调添加到以开始的数组大小为1。
当onRead
函数执行时,数组将包含1,000个回调函数。
答案 1 :(得分:0)
我的问题是我错过/忽略/忘记了javascript使用指针。这个问题让我走上正轨: How does variable assignment work in JavaScript?