Skip to content

Instantly share code, notes, and snippets.

@notcome
Created December 9, 2014 04:33
Show Gist options
  • Save notcome/33136373027b6c9ef204 to your computer and use it in GitHub Desktop.
Save notcome/33136373027b6c9ef204 to your computer and use it in GitHub Desktop.
ensure that the function's first invocation will be exclusive
var fs = require('fs');
function guardInit (init) {
var delayedCalls = [];
var status = 'not initialized';
return function () {
if (status == 'initializing')
return delayedCalls.push(arguments);
if (status == 'initialized')
return init.apply(null, arguments);
if (status != 'not initialized')
throw "你他么逗我";
status = 'initializing';
arguments = Array.prototype.slice.call(arguments);
var userCallback = arguments[arguments.length - 1];
if (typeof userCallback == 'function')
arguments = arguments.slice(0, -1);
else
userCallback = function () {};
arguments.push(function () {
userCallback.apply(null, arguments);
status = 'initialized';
delayedCalls.forEach(function (delayedArgs) {
init.apply(null, delayedArgs);
});
});
init.apply(null, arguments);
};
}
var dataset = ['/Users/LiuMS'];
var readdir = guardInit(function (id, callback) {
var path = dataset[id];
console.log('干我咯', path);
fs.readdir(path, callback);
});
for (var i = 0; i < 5; i ++) {
readdir(i, function (err, res) {
if (err)
throw err;
res = res.map(function (name) { return dataset[0] + '/' + name});
console.log('WOCAO', dataset, res);
dataset = dataset.concat(res);
console.log('WOCAOCAO', dataset);
});
}
console.log(dataset);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment