hash-gaming / robotk

Mostly helpful but sometimes trolly
MIT License
2 stars 1 forks source link

Promisify `msg.http` calls #19

Closed YashdalfTheGray closed 6 years ago

YashdalfTheGray commented 6 years ago

Right now, msg.http calls use Node.js style callbacks to do async operations. This can lead to callback hell if we start nesting callbacks so we will need promises sooner than later. Example below

// Callback hell

msg.http(url).get()((err1, res1, body1) => {
  if (err1) {
    msg.send('something has gone wrong');
  }
  else {
    msg.http(anotherUrl).get()(err2, res2, body2) => {
      if (err2) {
        msg.send('something has gone wrong');
      }
      else {
        msg.http(yetAnotherUrl).get()(err3, res3, body3) => {
          // now we have all the data if there is no error
          if (err3) {
            msg.send('something has gone wrong');
          }
          else {
            msg.send(body3);
          }
        });
      }
    });
  }
});
// With promises - assume that a function called fetch() is available

fetch(url).then(body => {
  return fetch(anotherUrl);
}).then(body => {
  return fetch(yetAnotherUrl);
}).then(body => {
  msg.send(body);
}).catch(e => msg.send('something has gone wrong'));

Much cleaner and much easier to read and it comes with a error handler built in just like a synchronous try/catch block.

Plus the http library that hubot is using is unmaintained.