Skip to content

Instantly share code, notes, and snippets.

@tomgp
Last active September 14, 2015 16:53
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 tomgp/43d5077c8f092932945f to your computer and use it in GitHub Desktop.
Save tomgp/43d5077c8f092932945f to your computer and use it in GitHub Desktop.
ES6 bits and bobs

##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"
}
}
'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);
}
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment