Ted's Tidbits

Do Promises Make Your Code Better?

In a post on GitHub, Dave Winer asks, “What do promises do/make possible that callbacks don’t?”

This is a great question, and one, IMHO, that is not often addressed or answered well. It often seems that developers embrace new patterns and API, taking for granted that they are better simply because they are newer.

This question brings me back to when I first had to work in a Promise-heavy codebase. It was five years ago, and I had very similar questions. The answers I got at the time weren’t very convincing. Here’s some sample code that uses the callback pattern:

request.get('http://api.someurl.com/api/resource', function (error, data) {
  if (error) {
      console.error('An error happened', error);
  console.log('Response received:', data);

Now, here’s the same code using the Promise pattern:

request.get('http://api.someurl.com/api/resource').then(function (data) {
  console.log('Response received:', data);
}).catch(function (error) {
  console.error('An error happened', error);

It’s different, but is it better? It really doesn’t seem to do anything that couldn’t be done with callbacks.

Where Promises started to shine for me was when I needed to compose multiple asynchronous responses. I provided code examples on the GitHub thread.

Dave replied with a link to some code he had written that had some pretty hairy logic involving many levels of nested callbacks.

I decided to refactor this code to use Promises, and then provide it as an example for further discussion of whether the Promise code is better or not. Along the way, I decided to take it a step further and I used some async functions and generator functions. I recorded my screen while I was making this edits. The finished product is on GitHub, the video is below.

Let me know what you think. Is this better or just different?

My Trip to Ghana

I recently returned from Ghana, West Africa where we spent a week at a children’s home called the Village of Hope. There are so many things to tell about this trip, but first here are some videos I made about what we did while we were there.

[youtube https://www.youtube.com/watch?v=wY0DgqTQga4?fs=1&hl=en_US&w=640&h=385]

[youtube https://www.youtube.com/watch?v=J-mgQ4SZAFM?fs=1&hl=en_US&w=640&h=385]

[youtube https://www.youtube.com/watch?v=ZcH5gK-nIbk?fs=1&hl=en_US&w=640&h=385]

[youtube https://www.youtube.com/watch?v=wAzEEQ7zaBs?fs=1&hl=en_US&w=640&h=385]