Asynchronous Javascript for Beginners (part 2)

Okay, so we’ve covered setTimeout( ). Let’s move on to AJAX.

AJAX (Asynchronous Javascript And XML) is where things get interesting. As you have have heard by now, the name AJAX is stupid. Most AJAX calls don’t actually use XML anymore, they use JSON. XML and JSON, by the way, are just different data exchange languages. Data exchange languages are different ways to format information and send it between different systems so that they can both understand it. So AJAX  is stupid, but to be fair though, we can all agree that it’s a way sexier name than AJAJ, so we’re sticking with it. I’ve heard the idea that you can think of the “X” as a variable for whatever data exchange language you want to use. I like that.

For now, we’re going to assume that we’re only using JSON. So AJAX now means ‘Asynchronous JS and JSON.’ Still not very descriptive. What does AJAX actually mean? Mainly, it just means getting JSON from another URL, or sending it. Boom. That’s mostly it, and I feel like that should have been conveyed somewhere in the acronym. It wasn’t, but it’s okay, we know now. We can take a deep breath and move on.

So the words in the AJAX acronym really just describe extra details about the main idea, mainly that this sending and receiving of JSON (or whatever) happens asynchronously. Take a look at this fiddle I found. It uses a JS method called fetch to do a bit of AJAX, namely a GET request. Change the code so that the JSON is logged to the console, then do like fifty console.log(“hello world)s or whatever you want right after the body of the fetch. As you can see, they all show up in the console first! Fetch is async, and as such it starts working, then stops for a while while the external server does its thing, letting the console.logs get to work until the fetch is ready to finish up and add its two cents to the console.

As you can now see, using AJAX means that async code become inevitable. In the next post, we will talk about the way async code has been dealt with traditionally, and the problems that arose as a result.




Asynchronous Javascript For Beginners (pt. 1)

Okay, no use beating around the bush. Asynchronous JS. What is is?

Probably the opposite of Synchronous JS, right? Let’s start there. Okay, what does ‘synchronous’ make you think of? Things happening at the same time. Synchronized swimmers. A team of bank robbers looking at their watches and yelling “Sync!” Stuff happening simultaneously. Which would make ‘async’ refer to things happening NOT at the same time. Right? Turns out, wrong.

Turns out, the definition is almost completely opposite. ‘Synchronous’ in programming doesn’t mean ‘at the same time’, but rather ‘one at a time, one after another.’ Synchronous programming just means that a series of events occur, and they occur in order:

  1. Thing 1 happens
  2. Thing 2 happens
  3. Thing 3 happens
  4. Thing 4 happens

Okay. So we’ve defined synchronous as one after another. Asynchronous code, on the other hand, will refer to code that starts running, and then for some reason has to stop in the middle, at which point later processes just start running AS IF that earlier thing was already done doing its thing. THEN, once that earlier process is ready to finish what it was doing, it picks up where it left off and finishes up.

  1. Thing 1 happens
  2. Thing 2 starts doing its thing and then is all like “Oh damn I actually can’t finish this right now, you guys go on without me”
  3. Thing 3 happens
  4. Thing 4 happens
  5. Thing 2 is like “Okay whew, I’m ready now” and finishes doing its thing.

So that’s Asynchronous Javascript. But what kind of things could Thing 2 be, that it needs to take so long to finish? This obviously isn’t just a list of console.logs, one after another. Here’s a list of things that make your code async, lifted from Byte Archer’s terrific post:

  • timer functions setTimeoutsetInterval
  • special functions nextTicksetImmediate
  • listening to network, querying a database
  • reading or writing, generally I/O from a resource
  • subscribing to an event

If you don’t want to go to far down the rabbit hole right now, just remember that the following two things are asynchronous: setTimeout( ) and AJAX.

If you play around a bit with setTimeOut( ) it won’t take long for you to see this in action. If you do a setTimeOut( ) with a console.log in it, followed by several other console.logs, you’ll see that the later ones don’t wait up for the async one, they just happen first.

We’ll pick up with Ajax in part 2.

How We Got To Redux (for people who blinked)

As we scramble to assemble our stacks of packages, routers, stylers, store persisters and the like, it’s worth it to take a moment  to breathe, look around and get a bit of perspective on what exactly it is that we’re doing and why we’re doing it. I’ll let you get back to trying to make thunk work in a second, but for right now we’re gonna look back, waaaaay back to the dark ages of 1994.

The darkness was rend in twain by the publishing of the book Design Patterns: Elements of Reusable Object-Oriented Software. The work was one of the first comprehensive collections of the development patterns  that programmers had discovered and re-discovered over the preceding decades. Among the patterns described was one called The Observer Pattern. The gist of it is that you have an object called the observer that contains all of your state. An app’s ‘state’ is just its memory of any events that have occurred or user interactions that have taken place. In many patterns, state ends up scattered all over the app, in a million different variables. In the Observer Pattern, however, your state is contained in one big object. It has listeners on it that connect to all the dynamic parts of your app. If a certain part of your state changes, so does the element connected by the listener.

Facebook first made React public in 2011 and open-sourced it in 2013. It was created by Jordan Walke. Despite the way we think of it now, React wasn’t just a vehicle to give us all Redux. At an F8 session in 2014, Tom Occhino, the Engineering Manager at Facebook, gave a talk where he outlined problems Facebook had encountered with the standard MVC application architecture, and announced something called Flux.

Flux was a design pattern, and architecture. It was not an actual product that Facebook had built, it was simply a way of doing things that had allowed Facebook to dramatically cut down on bugs and made their codebase easier to work on without fear of breaking things. As people outside Facebook began wanting to write in Flux as well, demand grew for a framework, an implementation of the Flux pattern. Facebook released a dispatch method and left it at that. Fluxify was written, as was Reflux.

Dan Abramov, while trying to work in Flux was growing frustrated. Not only did the existing implementations not suit his needs, he wanted hot reloading. On top of that, he had realized that using pure object actions with reducers on a pure object store would enable time-travel debugging, replaying an app’s change in state over time. On May 29 2015, he tweeted “Oh no am I really writing my own Flux library” and Redux, from “Reducer” and “Flux” was born.

In 2015, Abramov gave a presentation at React Europe that showed a workflow with hot reloading and time travel debugging, made possible with Redux. Since then, the React-Redux ecosystem has only grown, with packages for routing, styling, and much more becoming part of the React developer’s toolkit.

React on Rails, what could go wrong?

Just kidding, it wasn’t really that bad.  Everything I did can be broken down into the following phases:

  • Building the API
  • Building the React
  • Implementing Redux
  • Routing with react-router
  • Styling with react-bootstrap and react-router-bootstrap

Building the API

Easy! The Rails all came back like riding a bike, more or less. Had to do some googling to get syntax right, but by and large putting together a standalone API where I could see the JSON rendered at the routes I wanted it at was a breeze. For the most part, the problems I had were ActiveRecord stuff where the pluralization and capitalization conventions got away from me.

Much harder was linking up the front end to the API. I wanted to do some ‘fake’ authentication where I just kept a single sessions object alive in the database that told the app which user was logged in, and that ended up being a pain. I got it done, but it was hacky. It never fails to surprise me how much the restful actions in a controller can end up doing things that don’t line up at all with what they’re called.

A big hurdle was the fact that when people build Rails apps, they nearly always use form helpers that have a specific way of interacting with controllers. Since I was using JS, I had to understand exactly what kind of information a controller action expects to receive from a form in order to make it available in a ‘params’ object.

Building the React

My biggest trouble with the actual React was knowing how to structure my application, and I think that’s something that I’ll learn more about as time goes on. For example, for a brief moment I wanted to give my users profile pictures, but it was difficult to know where to store them. Should they even belong in the client directory? Seems like that would go in the Rails app/assets folder. Oh, but clients/src files won’t let you import files from outside of src?  A lot of things that seem pretty basic for an app are turning out to be harder than I thought, but I guess that can be said for most frameworks.

Implementing Redux

Definitely the most mind-stretching part of the project, and of learning React in general. I feel like I got a much better handle on the elements of Redux; it’s definitely nice to know that all the info lives in one spot. But then again, couldn’t that responsibility belong to the API? I felt a bit like the store was just working as a middleman between my front-end and my API in this project. Maybe that would be less the case in a situation where the API is just a resource, and doesn’t get mutated by the user’s interactions with the app.

Using fetch() correctly was probably the most difficult part of the entire project. It took me forever to understand that you can’t really return a vlue from a promise chain, you can only call a function in the final .then( ) call on the resolved promise from the second-to-last .then( ). That helped a lot, because I had some situations where I wanted to post info directly to the database instead of messing with state through dispatch( ).

Routing with react-router

After fetch( ), react-router was probably my biggest challenge. The biggest lesson that I learned in using it is that if you’re going to use react-router, EVERY component has to be nested in a Route. Otherwise, when you’re working in that component, you end up realizing that you want a link to take you somewhere, but you’re unable to do a this.props.history.push because props was never passed a  history object.  I ended up in a few situations where I ended up just using an anchor tag and an href because it seemed easier than going through the trouble of doing react-routes just for that one little component, but when most of your links use react-router, suddenly a full dom re-render feels much clunkier and more noticeable.  Doing react-router routes in all of my components is definitely something I’m going to have to accept as a fact of life from now on!

Styling with React-Bootstrap and React-Router-Bootstrap

I never got into bootstrap quite as deeply as I should have, but now I’m all about it! Things are a bit trickier than they were last time I learned about it, though; now I’m using bootstrap! react-bootstrap is a damn cool package with a what I think is a really cool, mutant logo. Pretty much everything that’s available in vanilla Bootstrap is available in the React version, with nearly documentation that looks exactly the same and everything. It was a little difficult adding custom css though, because I couldn’t find the downloadable files and had to use the CDN, so it was hard to know exactly what the css that I was overwriting looked like. Using the react-bootstrap grid system was something I couldn’t figure out either, so I left that for another day. I can’t wait, though. I want to make some components that actually LOOK like components.

One thing that creates problems, though, is that React-Bootstrap doesn’t make itself available as simple classes, but as finished, import-able components that you then give children to. Which is fine until you realize that React-Router works the exact same way. So now you’re trying to wrap a Route around a nav, but you want that nav to be a bootstrap nav, so what wraps around what? Spoiler: neither way works. Enter React-Router-Bootstrap! It gives you more or less nothing but a <LinkContainer> component, which is a bootstrap-friendly version of react-router’s  `<Navlink>` component.  We still need other react-router stuff though, so we have to hang on to that one!


I’m guessing that all this stuff will eventually get wrapped into React native, but it’s fun to see it in this phase, where everything still has to be cobbled together from five different sources. It’s certainly been interesting, and I’m looking forward to doing more with React.

Rails App w/ jQuery Frontend

I really enjoyed this project. It was basically just a revamping of the last project we’d done, replacing the front end ERB with JS and JQuery, and accessing the database through a Rails API instead of just using ERB.

The most important part of this project for me was understanding the concept of rendering what looks like a new route, but is just dynamic JS, made possible through an Ajax call to a backend Rails API. It would never have occurred to me to simply wipe the entire DOM clean and replace it with the content that makes up a new page, instead of loading the page itself from scratch. I was also struck by how much faster the loading time was, using this approach.

There were a couple of less abstract things I learned as well, specific methods and the like. The biggest deal was probably learning the alternate syntax for ‘.on’ that allows us to delegate an event to an element higher up in the DOM tree, usually ‘document.’ In other words, I learned the difference between this:

$('#id').on('click', function(){});

and this:

$(document).on('click', '#id', function(){});

The second option became extremely important for making listeners work when they were loaded dynamically. In this situation, the listeners had to be available pretty  much for every page on the app, since they all had access to the customers index that I rendered dynamically, without changing the route.

I also learned about history.pushState, which is necessary for making the URLs in the address bar look right, even if we didn’t technically use that URL to load the page.

Near the end of the project, I was creating a a dynamic version of the customer show page, and it struck me how silly it felt to be appending element after element to the body of the page, building it up one ‘plus equals’ at a time, in a function that kept getting bigger. It occurred to me that this was the sort of thing that React components were created to fix, and it got me pumped up for the upcoming React section of the course.


Building ‘Instrumental’ with Rails

Aaaaaand done.

Just finished my musical instrument rental service. There’s no CSS, and I’m a bit self-conscious about that; I have a friend also doing the learn course who makes his apps look flippin beautiful each time. Ah well, though. I’m happy with what I put together. It’s nice getting some real experience working with Devise, in particular. It feels like I’ve been working with Rails so long, it’s surprises me that this is my first Rails app.

I’m starting to realize that the hardest thing about programming can sometimes be all the different ways there are to do something. I’ve heard that Python only lets programmers do things one way, and I have to admit that the idea makes me feel a bit jealous. The issue isn’t only that there are fifty different ways to do Thing A and fifty different ways to do thing B, and having to make that choice, but that only certain ways to do Thing A are compatible with certain ways to do Thing B. I think if there’s a part of programming that intimidates me the most, that’s it. For example, I spent a lot of time in this app reviewing nested forms and custom attribute writers and understanding that writing custom nested form fields like this:

    <input type=”text” name=”user[addresses_attributes][ ][street_1]”>

<input type=”text” name=”user[addresses_attributes][ ][street_2]”>

….will result in an array of hashes in the params.


Most people don’t do this. Most people use the fields_for form helper, which uses the number of instances of address in the preceding #new method to generate THIS!

     <input type=”text” name=”user[addresses_attributes][1][street_1]”>

<input type=”text” name=”user[addresses_attributes][1][street_2]”>

    <input type=”text” name=”user[addresses_attributes][2][street_1]”>

<input type=”text” name=”user[addresses_attributes][2][street_2]”>

The difference? THIS code, instead of producing an array of hashes in the params, results in a hash of hashes which kind of ACTS like an array because the keys are numbers, but is NOT an array. So when you try to iterate through the addresses later in your custom writer, you have to make sure to include a param for the index as well or things break.


So that’s probably my biggest technical takeaway from the project. Also, I totally get Devise now. It’s pretty nice not having to deal with all of that security stuff, even if it gets annoying sometimes not to have access to my users controller. Interestingly enough, I kind of got used to not being able to work with users in the way I used to. I know there are ways to duplicate the controller and work with it anyway, but I’ll leave that can of worms on the shelf for now.

I also got a lot out of the project in terms of learning about task management and organization. There’s so much to do that I really have to have a system figured out, and near the end there I kind of became my own little SCRUM team.

So I’m sure I’ll look back on this project in a year and cringe like I never have before, but I’m pretty happy with this right now and everything I learned while doing it!

Building Comedy Connection w/ Sinatra

Woohoo! Just finished my Sinatra app. This was a fun one. I decided to relate my app to something I was interested in – namely, standup comedy – and it really made the project go much more smoothly. The result is Comedy Connection, a little app that lets you sign in as either a comedian to post your CDs and Specials, or as a fan to view different comedians’ pages, and add them to your list of favorites. Of course, you can also take a look at other fans’ pages and compare notes as to who likes who.

I think the biggest hurdle for me to overcome while working on this project was that of validation. I really didn’t know anything about it, and had to do a lot of reading before I understood it at all. Maybe this is just hope, but I’m starting to think that I’m getting better at reading the sort of technical material that was really hard for me to even start on before. Those `` pages are starting to feel a little more familiar and comfortable, and the barely-visible scroll bar is a little less scary than it was. I actually ended up getting kind of interested in validation and how the team that made Rails made the decision that model-level validation was the way to go, as opposed to database-level, controller-level or client-side.

Learning to write validations and use them is particularly interesting because of the responsibility that comes along with it. It’s pretty trippy to see the actual kind of code that’s supposed to protect people’s privacy, finances and so on. I understand that I have much further to go as far as validation and password protection go, but it’s still a pretty powerful feeling to realize that it’s all just code, really, and that there’s no magic keeping it all safe past what you’re able to design as a developer, and what tools you know how to use.

Another thing I really got better at through this project is associations. It really is the case that not matter what you study, at some point you just need to put in the reps if you want to actually have it on-hand in your mind. I realized that despite learning my AR associations, I couldn’t recall off the top of my head how to actually get a join table working. Ruby guides saved me again, and I’m making sure now to write down which areas I get stuck in, and quiz myself regularly on the details of how to get through them.

As hard as it was to really dive in and get started on this project, I’m glad I did it before waiting TOO long. I got an email from Peter Bell, the head instructor at Learn, reminding me that I’m not helping myself by working around the project, or delaying it. He was completely right, and I’m glad he gave me that little nudge to really hone in on the project. There are things about coding, it turns out, that you only learn when working on a project. I’m planning to meet the next one in a much more head-on fashion, and I’m looking forward to it!

He’s a bit more ‘CSS’ than ‘HTML’…

HTML. Structure. CSS. Style. Okay, I’m writing for other coders, you know this already. I’m a big fan of finding the crossover between ideas from coding and the rest of life. I think there’s real wisdom to be gleaned from each facet of programming.

So what’s the real message of the HTML/CSS paradigm? What’s the philosophy behind it? The idea, simply put, is that content is separate from style, and should be recognized as such. It doesn’t try to devalue style, or to render it somehow ‘less than’ content, but it draws a line in the sand with a statement that there is a difference, and that it matters. Knowing 100% what about your website, or yourself, is actual substance and what is style can be extremely useful.

When I use the words “style” and “substance” in reference to people, what I’m referring to are simply the things that are visible to the outside world, and those that are not. So “substance” in this case might refer to a persons inner beliefs, motivations, knowledge, emotions, life philosophy, etc. Their style might refer to their manner of speech, professed beliefs, clothing choices, physical appearance, charisma, posture, way of interacting with others, and so on.

Implying that a person is more style than substance is generally considered impolite in our society. However, I think it’s counterproductive to take that kind of view of the style/substance divide, whether it has to do with web design or everyday life. Humans hsve evolved to be naturally attracted to certain things – bright colors, interesting noises… that’s not going to change, and we shouldn’t feel bad about that. However, being drawn in by something that looks interesting on the surface and turns out not to be is infuriating in any context. It’s okay to favor style over substance or vice versa, but you need to have a bit of both.

This website for Johos Coffee is counterintuitive, hard to navigate and information light. However, it’s so cool to look at that its frustrations are easy to forgive.

On the other hand, here we have the well-known “hacker news” site from ycombinator. The site is unbelievably information dense and incredibly interesting, yet an outsider could be forgiven for thinking, on first glance, that it was designed by a third-grader. Personally, I thought I was at the wrong site the first three times I found it.

I’m a big fan of standup comedy, and I’ve always thought that Dane Cook was a fascinating case study in what can be accomplished with ‘style’, and what can’t. Cook was known for being extremely physical on stage, doing noises, imitations and totally unneccessary near-acrobatic movements that made you laugh despite yourself. There were jokes, there were ideas, but the sheer ridiculousness of his act was what really pushed things over the edge.

Where things started to go wrong was when his joke-writing started to suffer a little bit. Within a very short time, he became intensly hated by a huge contingent of comedy fans, becoming the butt of jokes and impressions that depicted him as a mindless, goofy acrobatic hack with nothing of substance to say.

This is the risk with going “full CSS.” People really hate style without substance. What’s the alternative? Well, I’m sure there’s a comedian out there who’s chock-full of substance but who puts you to sleep when you look at him. I don’t know that comedian’s name, and I probably never will. That’s the risk of going “full HTML.”

If you go for style without substance, prepare to be disliked. If you go for substance without style, prepare to be ignored. Both are necessary – as a designer and as a human being.

Can I be part of the future, please?

I think the first exposure I ever had to programming in any sense was from XKCD comics strips. I was just finishing college, with a not-quite-useless-but-close degree in Business Administration. The subject of the strip was related to computer science about half the time, but I would have to google punchlines before I could even understand the jokes. To be honest, learning a little aout programming was just a side effect of trying to understand the refences the comic made. But it worked. I still remember looking up Richard Stallman because XKCD had depicted him as a katana-weilding ninja, fighting copyright law. Humor is definitely the way to my heart, and I slowly started getting  sucked into the world of computers without even realizing it.

At this time I was also really starting to realize the value of an intellectually stimulating job. I had worked as a fry cook and a housekeeper at a hospital, and now I was working as a cashier at Publix (a grocery store chain in the southeast). It was the least mentally challenging job I’d ever had, and I swear that I could feel my mind slowing down. It felt like I was devolving into some kind of lower lifeform that stayed rooted to the ground like a polyp, only my hands moving, saying the same things over and over again. All I was missing was the ability to filter-feed nutrients from the air around me. It was less than ideal, and I was made very aware that once you leave school, nobody cares whether you keep learning or growing as a person anymore. That’s on you now.

Meanwhile, the world was computerizing at an impossible rate, and it seemed that all of the most interesting things that were happening were happening in tech. Facebook was considering putting wifi balloons into the sky, uber and airbnb were undercutting traditional business models, hackers and hacktivists were having real impact on politics, and so on. It felt like living in the 21st century without knowing how to program was like living in Viking times without knowing how to sail, or in Mongol times without knowing how to ride a horse. It was a prerequisite for the best adventures of the age. As I moved into my 20s, it seemed like if there was a time to jump on this bus, this was it.

So I started trying to learn how to program. I found codecademy, the “Hard Way” series by Ed Shaw and a slew of other resources. When I got stuck with one of them, I would just switch to another until I got stuck there, and then switch back. The fisrt thing I ever finished was the python class at codecademy. It was SO hard. I’m sure I’d probably laugh at it now, but I felt a huge sense of accomplishment finishing it.

The thing that really insipred me about programming was the fact that, seemingly, you could learn this amazing skill for free, assuming you had a computer to start with. I had messed around a little with electronics, and quickly learned that every project required cash to complete. Breadboards and multimeters cost money. They’re physical. There’s no open-source resistor. The real power of programming is that we can do so much with so little. A laptop, some electricity, and off you go.

Man, it’s nice to reflect on why I’m doing this. Haha, I’m all jazzed up now. Time to go study!

Check the Facts: my first CLI scraper

Welp, there it is. My Snopes CLI is up and running! Not gonna lie, that was a tough nut to crack. The cool thing about projects like this is that it takes you out of the Learn bubble and gives you a little push out into the scary, unending, bottomless sea that is development and lets you stay out there for a second, panicking, before you manage to clamber back onto shore.

I guess what I’m mostly referring to there is Nokogiri and XML, which I definitely still don’t really understand, but I’m way more comfortable with it now. I went into my project confident that I had chosen a website that was perfect for scraping and that I probably wouldn’t hit any major obstacles.

I found out how wrong I was when I realized that certain text elements I wanted to scrape didn’t have any unique selectors, and neither did their parents, but their CHILDREN did. No I tried to figure out how to select an element’s parent using CSS and it turns out… that CSS doesn’t have a parent selector. Bum bum baaaaah!

On one hand, bummer. On the other hand, it was a very interesting find; I love seeing debate in the development community about stuff like this.It reminds me how much this field is constantly evolving. CSS-tricks had a whole article about this issue, and apparently a bunch of programmers have proposed different potential syntaxes for a parent selector, but it was left out of CSS3 due to the potential for overuse. I wondered if I would have to scrap the project.

BUT! Guess what DOES have a parent selector? XM friggin’ L. It took me a minute, but after learning a bit about XML, nodes, and all that jazz, I was able to get what I wanted. Definitely useful and definitely an area for me to explore more later.

Other than that, things went more or less smoothly. Had a period of time where I kept recieving 404s from the scraper, but that kind of just went away by itself somehow. That’s  a little frustrating, not knowing why, but at least I got past it. I have to say though, I’m glad I chose Snopes for this project. It was fun working on something where I would occasionaly also see confirmation that Cracker Barrel is not, in fact, changing its name to ‘Caucasian Barrel’ under pressure from liberals.