-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinconsistentRead.js
37 lines (31 loc) · 975 Bytes
/
inconsistentRead.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const fs = require('fs');
const cache = {};
function inconsistentRead(filename, callback) {
if(cache[filename]) {
//invoked synchronously
callback(cache[filename]);
} else {
//asynchronous function
fs.readFile(filename, 'utf8', (err, data) => {
cache[filename] = data;
callback(data);
});
}
}
function createFileReader(filename) {
const listeners = []; inconsistentRead(filename, value => {
listeners.forEach(listener => listener(value)); });
return {
onDataReady: listener => listeners.push(listener)
};
}
const reader1 = createFileReader('data.txt');
reader1.onDataReady(data => {
console.log('First call data: ' + data);
//...sometime later we try to read again from the same file
const reader2 = createFileReader('data.txt');
reader2.onDataReady( data => {
console.log('Second call data: ' + data); });
});
});
// 考察输出结果,涉及知识点异步、时间循环等