Posted in JavaScript, workshops

JavaScript Promises

Today, I attended a workshop about JavaScript Promises. I had used promises once before, without really understanding them, and I definitely wasn’t at a point where I could explain what they were or why they were necessary. Today was helpful, though I think I’m only one inch further along in my understanding.

In order to reinforce my own learning (and maybe help some other newbies out), I think I’ll recap the skills that I tackle each day and try put them into easier-to-understand terms.

What is a promise?

JavaScript is “single-threaded”, meaning that multiple tasks can not run at one time. Each task runs sequentially, one after the other. Unfortunately, this means that if task2 relies on information returned by task1, it might run task2 before task1 has returned anything, causing task2 to return undefined.

For example: If you want to edit a user’s email address, you would first have to search for that user’s information. So, you’d query the database (task1), looking for a ‘user’ whose current email address is johnsmith@fake.com. Then, we’d want to wait for the database to return John Smith’s information. Unfortunately, JavaScript doesn’t know how to wait for the database. Since JavaScript has completed it’s job with task1, it’s going to move on to task2 even if the database hasn’t returned the information that we need yet. When task2 runs, JavaScript will get to the bit about our ‘user’, and have no idea who the ‘user’ is, since it didn’t stop and wait for a response in task1.

This is where the “promise” comes in. It essentially acts as an IOU. JavaScript runs task1 and says, “Ok, I know you asked me for this ‘user’ thing. I’m going to do my job and ‘.then’, whenever I hear back from the database, I’ll remember that you wanted something called a ‘user’.”

Still confused?

Maybe I am too…but not quite as confused as I was before I took the two hour workshop. The instructor (a T.A. from Fullstack Academy) was very helpful. Though I felt bad that I was the only one of the 12 RSVPs to show up to the workshop, it certainly was nice to get one-on-one instruction in this. He recommended I watch this video to strengthen my understanding of why promises are necessary:

Additionally, this site does a much better job of explaining promises than I did:

https://scotch.io/tutorials/javascript-promises-for-dummies

To view the tutorial exercises, check out the forked repo:
https://github.com/jepetersohn/promises-public
The solutions are in my branch.

Advertisements