RSS

Tag Archives: promise

Promises rejection (..but with style)

I find handy define this kind of function in my code:

function if_error(reject, err) {
  if (err) {
    console.error(err);
    reject(err);
  }
}

Now when I’ll need to handle a rejection, my code will be

something.can('go-wrong', (err) => {
  if_error(reject, err);
  ...

It’s something between pure functional programming and very readable code.

 
Leave a comment

Posted by on 2017/05/16 in dev

 

Tags: ,

I promise you a working jsdom

Working with jsdom is incredible, but most of the times you feel drowning in the callback hell
.
Here’s a template (soon on my github) that makes everything oven-ready 😉

var request = require('request');
var jsdom = require('jsdom');
var promise = require('promise');
var colors = require('colors');
var util = require('util');

function get(url) {
  return new Promise(function (resolve, reject) {
    console.log('>>>'.yellow, 'started', 'get'.cyan, '[', url.yellow, ']');

    request(url, function(err, res, body) {
      if (!err && res.statusCode == 200) {
        console.log('>>>'.yellow, 'done'.green, 'get'.cyan, '[', url.yellow, ']');
        resolve(body);
      }
      else {
        console.log('get error:'.red);
        if (res && res.statusCode)  console.log('  res:' + util.inspect(res.statusCode));
        console.log('  err:' + util.inspect(err));
        console.log('- - - - -'.red);
        reject(err);
      }
    });
  });
}

function buildDOM(body) {
  return new Promise(function (resolve, reject) {
    console.log('>>>'.yellow, 'started', 'buildDOM'.cyan, 'on', body.length, 'bytes');
    jsdom.env(body, ["http://code.jquery.com/jquery.js"], function(err, window) {
        if (typeof(window) === 'undefined') {
          console.log('buildDOM Error'.red + ': ' + util.inspect(err));
          reject(err);
        }
        else {
          console.log('>>>'.yellow, 'done'.green, 'buildDOM'.cyan);
          resolve(window.$);
        }
      }
    );
  });
}

function parse($) {
  return new Promise(function (resolve, reject) {
    console.log('>>>'.yellow, 'started', 'parse'.cyan);
    try {
      var result = $('input[name="btnI"]');
      console.log('>>>'.yellow, 'done'.green, 'parse'.cyan);
      resolve(result.attr('value'));
    }
    catch (ex) {
      console.log('Parse Error'.red, util.inspect(err));
      reject(ex);
    }
  });
}

function log(x) {
  console.log('>>>'.yellow, 'started', 'logging'.cyan);
  console.log('[',x,']');
  console.log('>>>'.yellow, 'done'.green, 'logging'.cyan);
}

get('http://www.google.com').then(buildDOM).then(parse).then(log);

And, as always, under 100 lines of code! =)

 
Leave a comment

Posted by on 2015/10/15 in dev

 

Tags: , , ,