Skip to content

Instantly share code, notes, and snippets.

@AndrewThian
Created April 8, 2019 04:53
Show Gist options
  • Save AndrewThian/2ac592460e282c279f4501fcd10bf644 to your computer and use it in GitHub Desktop.
Save AndrewThian/2ac592460e282c279f4501fcd10bf644 to your computer and use it in GitHub Desktop.
How does a race condition happen when we return both a synchronous callback and asynchronous callback!
const fs = require('fs');
const cache = {};
function zalgoRead(filename, cb) {
const file = cache[filename];
if (typeof file !== 'undefined') {
console.log('reading from cache');
cb(null, file);
return
// return process.nextTick(() => {
// cb(null, file);
// })
}
fs.readFile(filename, function (err, data) {
if (err) {
return cb(err, null);
}
cache[filename] = data;
return cb(err, data);
});
}
function reader(filename) {
const listeners = [];
zalgoRead(filename, function (err, data) {
console.log('listeners size:', listeners.length);
listeners.forEach(function(listener) {
console.log('calling listener');
listener(err, data);
});
});
return {
addListener: function (listener) {
console.log('adding listener');
listeners.push(listener);
},
};
}
reader('hello.txt').addListener(function (err, data) {
console.log(`First read: ${data.toString('utf8')}`);
// reading from cache will execute the listener before the next tick, which in turn
// calls the callback before we have added a listener!
reader('hello.txt').addListener(function (err, data) {
console.log(`Second read: ${data.toString('utf8')}`);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment