Promise chaining vs async/await

Oh man, in my React/Redux final project, which uses New York City’s open data to create a dashboard for city renters, I ended up having to chain a lot of API GET requests together because of the way the data was organized.

For instance, to get a building’s Registration Info (information about building owner and manager), I had to first lookup a building’s Building Identification Number (BIN) in one dataset, cross-reference than BIN with a Registration ID in another, and use the Registration ID in a third to finally come across the Registration Info.

And all that resulted in (assume fetchBin, fetchRegId, and fetchRegInfo are the appropriate API calls:

export function getRegistrationInfo(address) {
  return dispatch => {
    dispatch({ type: 'GET_BIN', address });

    return fetchBin()
      .then(
        response => {
          dispatch({ type: 'GOT_BIN', address, response });
          dispatch({ type: 'GET_REG_ID', address });

          return fetchRegId()
        }
      )
      .then(
        response => {
          dispatch({ type: 'GOT_REG_ID', address, response });
          dispatch({ type: 'GET_REG_INFO', address });

          return fetchRegInfo()
        }
      .then(
        response => {
          dispatch({ type: 'GOT_REG_INFO , address, response});
        }
      )
  }
}

I just don’t like it. Maybe some people like chaining these Promises because it’s like a timeline or something, but I think it just looks bad!

Enter async and await. Unfortunately I didn’t know about them until my code review, but I wish I had! Introduced in ES2017, it’s a new way to handle asynchronous functions in JavaScript!

async allows you to declare a function that will return a Promise. More importantly, async functions can contain await expressions that pauses execution while the expression is resolved. Using async/await, I could refactor the above code as follows:

export async function getRegistrationInfo(address) {
  return dispatch => {
    dispatch({ type: 'GET_BIN', address });
    const binResponse = await fetchBin();
    dispatch({ type: 'GOT_BIN', address, binResponse });

    dispatch({ type: 'GET_REG_ID, address });
    const regIdResponse = await fetchRegId();
    dispatch({ type: 'GOT_REG_ID', address, regIdResponse });

    dispatch({ type: 'GET_REG_INFO, address });
    const regInfoResponse = await fetchRegInfo();
    dispatch({ type: 'GOT_REG_INFO, address, regInfoResponse });
  }
}

To me, that looks so much better and simpler. I understand there are some difficulties with error catching when using async/await, which I’ll have to look more into. And I admit that my Promise chaining did not look as neat as the example I have above, which isn’t that bad, because I hadn’t seen the proper way to do it, as detailed here. I had been indenting with every then, which was just getting crazy…

Anyway, at least it’s another option I now know about!

What’s going on with 18F and The U.S. Digital Service?

While writing my last blog post about tech-for-good and civic tech, I was reminded about how much I used to talk about the 18F and U.S. Digital Services programs of the Federal government. They were founded during the Obama administration to bring modern technologies and processes to Washington.

I wondered: what has happened to them over the last two years? Are they still thriving and innovating under a much different regime?

Wait, 18 what and the U.S. Digital who??

18F

18F (named for the intersection—18th St and F St—in Washington, DC where they’re headquartered) is a “an office of federal employees within the General Services Administration (GSA) that collaborates with other agencies to fix technical problems, build products, and improve how government serves the public through technology.”

They partner with other agencies in the federal government to build digital services utilizing lean startup practices, they are dogmatic about developing with transparency (open-source), and they aim to leave their partner agencies with a sense of how software development looks outside the massive bureaucracy of the federal government.

Some of their earliest work includes:

  • https://analytics.usa.gov/, which displays Google Analytics data for many government websites. In case you’re interested, the government website with the most users at the moment I’m writing this is the USPS’s tracking page. By far.
  • https://collegescorecard.ed.gov/, a website which allows users to compare the cost and value of colleges throughout the United States.
  • https://myra.gov/, a website for the Treasury Department’s myRA program, which was a government-sponsored Roth IRA account.

U.S. Digital Service

The U.S. Digital Service is actually within the Executive Office of the President—the “White House”—so it has a more top-down approach. It recruits top technologists for short-term stints in the government to work on the Administration’s top priorities. It was created after th HealthCare.gov rollout disaster to prevent something like it from ever happening again.

Some of their earliest work:

  • https://my.uscis.gov/ (in partnership with 18F), a website for helping users navigate through the immigration process.
  • https://www.va.gov/, a website for Veterans to discover, apply for, track, and manage their benefits.
  • IRS Secure Access, which allows taxpayers to access their tax transcripts online, rather than through the mail.

Changes under Trump

With Trump coming into office, many were worried that these programs’ futures were grim at best. And while there certainly have been changes and large reductions in staff—at least at 18F—both still exist and are doing good work! The U.S. Digital Service is actually still run by an Obama-era hire!

18F

According to Fast Company, 18F’s staff headcount has shrunk by at least half since Trump’s inauguration, and many staff resigned in protest of Trump’s policies and personal behavior. However, there are still civil servants there hard at work, making sure the good work started under Obama continues. In fact, just this month, they released the second version of their design guidelines for new government websites—the United States Web Design System 2.0.

U.S. Digital Service

Because the U.S. Digital Service is focused on advancing the priorities of the White House, I am more surprised to find that it is still operational, and even more surprised that it’s being run by Matt Cutts, who was there during the Obama administration. And it looks like I’m not alone in that thinking, with numerous articles referencing it (just search “matt cutts trump”). It appears the common response is that their crew is actually nonpartisan, working for the “American People.”

And they have done some great things, like saving the VA $100 million by streamlining their cloud infrastructure processes, and helping to build anti-drone defenses. And right now, they’re working on upgrading Medicare’s payment system, which is apparently 40 years old and written in COBOL and assembly.

But it’s weird to see that they’re working on helping immigrants and refugees, when that’s clearly anathema to the White House. I hope they can continue to do that kind of work without Mr. Trump ever finding out about it!

Ruby existentialism

What is the self? Philosophers have been pondering that question for centuries. Luckily, we don’t have to worry about such complex contemplation when we consider self in object-oriented programming (also called this or Me, depending on the language).

Recap: object-oriented programming

Object-oriented programming is a paradigm in which state (data) and behaviors that operate on or with that data are encapsulated in objects. In a way, objects in programming are similar to real-life objects—they have attributes and can do different things depending on those attributes.

A class is a template for creating objects, and contains definitions of the data formats and available behaviours for all instances of itself. For instance, if we were representing a car in code, we could have a Car class that defines all car objects as having attributes, such as color, horsepower, weight, etc., as well as behaviors, like accelerate, that would act differently depending that object‘s specific attributes:

class Car

  attr_accessor :color, :horsepower, :weight
  
  def accelerate
    ...
  end

end

attr_accessor allows us to get and set the attributes of an object. Here’s it’s letting us get or set a Car‘s color, horsepower, and weight.

Self keyword

When we’re defining the behaviors in a class, we need to have a way to access the data of a specific instance of that class (an object). In Ruby, as in many other languages, we use the keyword self. Objects are self-aware!

In our Car example, let’s say we want to define the accelerate behavior (method in Ruby) as returning the specific Car object’s horsepower divided by its weight (a vast simplification). We would define it like this:

def accelerate
  self.horsepower / self.weight
end

Let’s do it for real!

Ok, we’re going to write a program to pass Learn’s “Object-Oriented Counting Sentences” Lab. We’re going to be monkey patching Ruby’s String class with a few additional methods:

  1. #sentence?
    Returns true if the String object it’s called on is a sentence (ends with a period).
  2. #question?
    Returns true if the String object it’s called on is a question (ends with a question mark).
  3. #exclamation?
    Returns true if the String object it’s called on is an exclamation (ends with an exclamation point).
  4. #count_sentences
    Returns the number of sentences in a String object. In this case, a “sentence” can end with a period, question mark, or exclamation point.

Remember, we can use the self keyword in our method definitions to refer to the String object on which it is called. Let’s look at an implementation of our first three methods (hint – use the #ends_with? method to check the last character of a String):

class String

  def sentence?
    self.ends_with?('.')
  end

  def question?
    self.ends_with?('?')
  end

  def exclamation?
    self.ends_with?('!')
  end

end

For our final method, we just have to count the number of periods, question marks, and exclamation points, right?!?!?!? Well, that would work as long as people don’t use multiple marks in a row, like I just did. Instead, let’s count the number of substrings that end with one or more of these marks. For that, we can use our friend the #split method and a regular expression.

Do you remember how you’d write a regular expression for “one or more of periods, question marks, or exclamation points?” I recommend Rubular for checking RegExes in Ruby. Don’t continue until you’ve figured it out!

Yep, it’s /[.!?]+/. Note that you don’t need to escape characters inside the brackets. So, our final method inside the String class would look like this:

def count_sentences
  self.split(/[.!?]+/).count
end

That’s it!

Is technology good?

“Who are we doing this for?”

I think we have to ask ourselves that question whenever we’re working on a project—and I think it’s a question a lot of people in the tech industry (and those who fund it) have been forgetting to ask themselves.

Technology can be an amazing and powerful tool that can help solve global problems, spark joy in people, and literally save lives. But it can also do the opposite, which is a part of why tech has gotten a bad reputation over the last few years. Russia used social media to meddle in the 2016 U.S. elections. Facebook provided Cambridge Analytica with 87 million users’ private information. Google gave a $90 million exit package to an executive after he was fired due to sexual misconduct. And that’s just the tip of the iceberg—think about how your own views of tech have changed.

These kinds of things happen when the focus of those developing technology is solely on growth and creating value for shareholders, with none on the wellbeing of the user. Sure, you have to consider that companies need money to survive, but there needs to be a balance between that need and protecting the interests of consumers.

The double (or triple) bottom line

In New York City, and around the globe, there is a growing interest in the idea of “tech for good” enterprises, which not only focus on profit, but also on social value—a so-called double bottom line. This is not a new idea in general, but one that is nascent in the tech community. A triple bottom line model—one that combines user, social, and economic impact, is also common in the tech-for-good conversation.

One way companies are declaring their double or triple bottom lines is by registering as certified B-Corporations (operated by the nonprofit B Lab), which are “legally required to consider the impact of their decisions on their workers, customers, suppliers, community, and the environment.”

Civic Technology

One slice of the tech-for-good pie that I’m specifically interested in is Civic Technology, which is “technology that’s spurring civic engagement, enhancing citizen communications, improving government infrastructure, or generally making government more effective.”​*​


  1. ​*​
    http://archive.today/zlWwF

Why software development?

Welcome to the first entry in my Flatiron School blog! I’ll follow their recommendation in writing about why I decided to take a software development course at this point in my life.

TL;DR

The short version: coding is one of the only things I can just sit and do for hours, without realizing how fast time is passing by. And I am a big believer in the mantra of “do what you love.”

The long version

In hindsight, it was not a good idea to combine roller hockey and baseball into a single sport. But it was the summer of 1999 and my brother and I were 9 and 10 years old, respectively. And we had just transitioned from spending our days at a baseball camp to a roller hockey one, so the combination seemed natural!

I sprint-skated down the base line, rounded first, but realized I should not advance. So I tried to quickly stop, fell hard backwards, and broke my wrist. I wound up leaving the hospital in a cast and doctor’s orders not to continue playing hockey. But that might have been a lucky break!

In our search for a camp I could attend without needing to use my arm that much, we settled upon ACE Computer Camp. I was already pretty into computers—I had convinced my parents to get that newfangled “Internet” thing—but knew nothing about programming. But I instantly fell in love my first day at camp, when I first started learning BASIC.

I ended up attending ACE for 10 weeks over the next three years, until it unfortunately ceased operations in 2001. Over those three years, I learned BASIC, Java, and C++. My final project was a C++ implementation of BattleShip in which you could play against a computer player that was actually good! I even teamed up with a few of my friends to start a “company” called LavaWare, which released games and utilities for free online. In writing this blog, I was sad to find out that even the Wayback Machine couldn’t render any of our pages from ~20 years ago. However, I was able to find some glorious images!

Logo
Lava Ware was the parent company of “daibouken software productions”

Anyway, as I went on to high school, coding kind of faded away—what was offered at my school was less advanced than I already was—and I focused on science and math. I was on the track and swimming teams, and did theater. By the time I got to college, it had been more than five years since I had done any coding…

I majored in Biology, but I kind of wish I had done Computer Science—I think I would have enjoyed it much more. I did end up taking classes in Java, C, C++, which were great, but for some reason it never occurred to me to switch majors.

I left Stanford in 2011 for a job with President Obama’s reelection campaign (politics are another passion of mine), doing major-donor fundraising in San Francisco. After we won in November of ’12, my team founded Tech4America (T4A.org), a nonprofit that convened public sector leaders with tech-sector leaders with the goal of creating public-private partnerships. In 2015, I moved to New York, where I continued working in politics through 2016. With a heavy heart following my campaign’s loss in November, I went through a long period of soul-searching and thinking about my future.

When I thought about what I really loved to do, I couldn’t stop coming back around to coding. So here I am!