tomgp
9/14/2015 - 4:49 PM

ES6 bits and bobs

ES6 bits and bobs

'use strict';

const request = require('request');

getPage('http://www.toffeemilkshake.co.uk')
	.then(function(page){
		console.log(page);
	})
	.catch(function(reason){
		console.log('Failed :( ', reason);
	});	


function getPage(url) {
	return new Promise(
		function (resolve, reject) {
			request(url, function (error, response, body) {
				if (!error && response.statusCode == 200) {
					resolve( body );
				}else{
					reject(' REJECTED ' + error);
				}
			})
		});
}

##request-promise.js

Request is my go to library for doing http stuff in node.js applications. It greatly simplifies the process of making and handling http calls. Now that Node 4 is out and we can use promises out of the box (along with all sorts of other nice ES6 features) you may want to take advantage of this more straightforward paradigm (I'm aware of the request-promises and a few other libraries offering this kind of http reqests & promises but I think that with native promises we shouldn't need anything else in the mix).

This here is a minimal example, showing how you might wrap calls to the request library in a promises. All it does is get a copy of my homepage and console.log it.

To get it running on your computer you'll want to have a recent version of node.js (ie. version 4+). Run npm install to install request and type node request-promise.js to run the script.

{
  "name": "es6-bits-and-bobs",
  "version": "1.0.0",
  "description": "wrap a requests call in a ES6 promise",
  "main": "",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "tom.g.pearson@gmail.com",
  "license": "ISC",
  "dependencies": {
    "request": "^2.61.0"
  }
}