Last active
August 14, 2017 15:13
-
-
Save KinoAR/c710f38a5541b8cb96fcc03c1905e356 to your computer and use it in GitHub Desktop.
An example of the cat HTTP request function using promises.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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