On Github AndreTheHunter / promises-presentation
Created by André de Jager
Normal HTTP.request
var request = require('http').request; var req = request('https://api.github.com/', console.dir); req.on('error', console.error);
Promise version
var request = require('request-promise'); request('https://api.github.com/') .then(console.dir, console.error);
var fs = require('fs'); var dir = '/Users/andre.dejager/Coding/'; fs.exists(dir, function (exists) { if (!exists) return; fs.readdir(path, function (err, files) { if (err) return console.error(err); files.forEach(function (file) { fs.stat(dir + file, function (err, stats) { if (err) return console.error(err); console.log(stats.size); }); }); }); });
var exists = require('./exists'); var promisify = require('promisify-node'); var fs = promisify('fs'); var dir = '/Users/andre.dejager/Coding/'; exists(dir) .then(function (exist) { if (!exist) return; return fs.readdir(dir); }) .then(function (files) { files.forEach(function(file) { fs.stat(dir + file).then(function (stat) { console.log(stat.size); }, console.error); }); }) .catch(console.error);
var fs = require('fs'); module.exports = function (path) { return new Promise(function(resolve, reject) { fs.exists(path, resolve); }); };
var fs = promisify('fs'); module.exports = function readdir(dir) { return new Promise(function (resolve, reject) { fs.readdir(dir, function (err, files) { if (err) return reject(err); resolve(files); }); }); };