Skip to content

Instantly share code, notes, and snippets.

@KinoAR
Last active Aug 14, 2017
Embed
What would you like to do?
An example asynchronous function from a project of mine.
const path = require('path');
const http = require('http');
const URL = require('url').URL;
const RichEmbed = require('discord.js').RichEmbed;
const url = new URL('http://random.cat/meow');
module.exports.run = function ({ client, message, args }) {
/* Get cat function that takes a callback function to
* work with the new cat picture data.
*/
getCat((data) => {
const catEmbed = new RichEmbed({ title: 'Meow' })
catEmbed.setImage(data.file);
message.channel.send("Nyaa ~ :cat: ", { embed: catEmbed })
.then(message => console.log(`Sent message: ${message.content}`))
.catch(console.error);
});
};
/* getCat function that creates an HTTP request (asynchronous)
* and supplies the data to the cat picture.
*/
function getCat(callback) {
http.get({
hostname: url.hostname,
path: url.pathname,
pathname: url.pathname
}, (res) => {
res.setEncoding('utf8');
let rawData = '';
//Passes data to the rawData function.
res.on('data', (data) => {
rawData += data;
});
//Once all data is passed, parse the JSON string that is returned by the end event.
res.on('end', () => {
callback(JSON.parse(rawData));
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment