Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active August 14, 2017 15:13
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 KinoAR/c710f38a5541b8cb96fcc03c1905e356 to your computer and use it in GitHub Desktop.
Save KinoAR/c710f38a5541b8cb96fcc03c1905e356 to your computer and use it in GitHub Desktop.
An example of the cat HTTP request function using promises.
const path = require('path');
const http = require('http');
const URL = require('url').URL;
const url = new URL('http://random.cat/meow');
/* getCat function that creates an HTTP request (asynchronous) and
* supplies the data of the cat picture through a promise.
*/
function getCat() {
return new Promise((resolve, reject) => {
http.get({
hostname: url.hostname,
path: url.pathname,
pathname: url.pathname
}, (res) => {
res.setEncoding('utf8');
let rawData = '';
res.on('data', (data) => {
rawData += data;
});
res.on('end', () => {
/* Runs the resolve function when the request ends. */
resolve(JSON.parse(rawData));
});
res.on('error', (err) => {
console.log(err);
/* Runs the reject function if an error occurs. */
reject(err);
});
});
});
}
/* Get cat function that returns a promise. */
//ES6
getCat().then(data => {
console.log(data);
});
//ES5
getCat().then(function (data) {
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment