Hubot + ES6 + Promises

Kees C. Bakker
Jan 19, 2018 · 3 min read

I like to drink my coffee, instead of scripting it

const norrisUrl = 'https://api.icndb.com/jokes/random';// wrap with promise
new Promise((resolve, reject) =>
robot.http(norrisUrl).get()((err, response, body) =>
err ? reject(err) : resolve(body)
)
)
// parse to js object
.then(body => JSON.parse(body))

Let Hubot listen in

const
norrisUrl = 'https://api.icndb.com/jokes/random',
decode = require('decode-html');
//the export is used to init the bot
module.exports = (robot) => {
//listen to phrases that contain "Norris"
robot.hear(/Norris/i, (res) => {
//wrap the HTTP get call as a Promise
new Promise((resolve, reject) =>
robot.http(norrisUrl).get()((err, response, body) =>
err ? reject(err) : resolve(body)
)
)

//parse to js object
.then(body => JSON.parse(body))
//get joke - jokes may have stuff like "
.then(json => decode(json.value.joke))
//reply joke
.then(joke => res.reply(joke))
//problems? Annoy the user with the problem
.catch(err => res.reply('Not even Chuck Norris can deal with this one: ' + err));
});
};

And action!


wehkamp-techblog

We'll try to keep up and post on the stuff we're doing and discovering. Interesting in working @wehkamp? Check out https://werkenbij.wehkamp.nl/

Kees C. Bakker

Written by

I work as a Lead Developer for one of the biggest web-shops in the Netherlands: wehkamp. I ❤️ C# and I like to solve nifty problems.

wehkamp-techblog

We'll try to keep up and post on the stuff we're doing and discovering. Interesting in working @wehkamp? Check out https://werkenbij.wehkamp.nl/