Skip to content

Instantly share code, notes, and snippets.

@rhapsodyn

rhapsodyn/cap.js Secret

Created July 9, 2014 12:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhapsodyn/b1daceb4d2f1da514aaf to your computer and use it in GitHub Desktop.
Save rhapsodyn/b1daceb4d2f1da514aaf to your computer and use it in GitHub Desktop.
callback vs async vs promise
var fs = require("fs"),
path = require("path"),
async = require("async"),
Q = require("q");
//first version
// var dirName = "foo";
// fs.readdir(dirName, function(err, fileNames) {
// if (err) {
// throw err;
// }
// var readCount = 0;
// fileNames.forEach(function(fileName) {
// var fullPath = path.resolve(dirName, fileName);
// fs.readFile(fullPath, function(err, data) {
// if (err) {
// throw err;
// }
// console.log(data.length);
// if (++readCount == fileNames.length) {
// console.log("DONE");
// }
// });
// });
// });
//second version
// var dirName = "foo";
// fs.readdir(dirName, function(err, fileNames) {
// if (err) {
// throw err;
// }
// var fullPaths = fileNames.map(function(fileName) {
// return path.resolve(dirName, fileName);
// });
// async.map(fullPaths, fs.readFile, function(err, datas) {
// if (err) {
// throw err
// }
// datas.forEach(function(data) {
// console.log(data.length);
// });
// console.log("DONE");
// });
// })
//third version
var readdirPromise = function(dirName) {
var deferred = Q.defer();
fs.readdir(dirName, function(err, fileNames) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(fileNames);
}
});
return deferred.promise;
};
var readFilePromise = function(filePath) {
var deferred = Q.defer();
fs.readFile(filePath, function(err, data) {
if (err) {
deferred.reject(err);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
// below two lines are AWESOME!
// var readdirPromise = Q.denodeify(fs.readdir);
// var readFilePromise = Q.denodeify(fs.readFile);
var dirName = "foo";
readdirPromise(dirName).then(function(fileNames) {
var readFilePromises = fileNames.map(function(fileName) {
var fullPath = path.resolve(dirName, fileName);
return readFilePromise(fullPath);
});
return Q.all(readFilePromises);
}).then(function(datas) {
datas.forEach(function(data) {
console.log(data.length);
});
console.log("DONE");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment