Promises – What are they and why should I care? – What?



Promises – What are they and why should I care? – What?

0 0


promises-presentation


On Github AndreTheHunter / promises-presentation

Promises

What are they and why should I care?

Created by André de Jager

What?

What is a Promise?

  • Promises contain a future value
  • For asynchronous code
  • Chainable and nestable
  • Not a new idea, but a standard
All parts that use async e.g. http requests, file system, database

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);

Why?

Why use Promises?

  • Alternative to callback hell (pyramid of doom)
  • Shallower, more readable code
  • Easier error handling
  • Forward compatible
Works great with generators

Callback hell

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);
      });
    });
  });
});

Promise heaven

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);

How?

How do I use Promises?

  • One constructor
  • Call appropriate function (resolve or reject)
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);
    });
  });
};

When?

When can I use Promises?

  • Part of ES6 (ECMAScript 2015)
  • Already in V8 (Chrome, iojs)
  • Can be pollyfilled!
  • Client and server side (Node.js)

Links

Promises What are they and why should I care? Created by André de Jager