2013-08-24 5 views
0

a presentation (슬라이드 50-51)은 저자가 Node에서 10000 개의 동일한 파일 읽기 콜백을 배치하는 방법에 대한 예제를 제공합니다. 초보자 노드 개발자로node.js의 가변 모집단 및 콜백

// 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];)를 포함하는 배열로 설정하는 방법을하지 않는이 예에서는 한 가지입니다, 아직 10000 콜백을 포함 할 수있는 방법 onRead의 기능은 무엇입니까?

은 내가 onRead 함수가 이벤트 큐에 넣어되고 batchingReadFile 기능이 모두 10000 번 호출 될 때까지 호출되지 얻을,하지만 여전히, 어떻게 다른 콜백 함수는 callbacks에서 끝나는가?

나는 아주 분명한 것을 놓치고 있습니까? 그렇다면 부드럽게 나와 나를 향해 지적하십시오.

답변

0

코드를 놓친 것처럼 보입니다.

if (filename in requestBatches) { 
    requestBatches[filename].push(callback); 

    return; 
} 

...이 batchedReadFile 연속적인 호출은 동일한 파일명과, 그 콜백 배열에 추가 보장받을하는 때에는 크기 1

에서 오프 개시 onRead 기능이 실행 배열은 012 콜백 함수가 포함 된입니다.

+0

예, 그들은 "requestBatches"변수에 추가되지만 "onRead"에서 사용되는 "콜백"입니다. –

관련 문제