JavaScript is pretty dumb. I know its the most popular language right now (due to the pervasiveness of browsers and other things that can run it), but, I mean, its just… dumb.
Luckily TypeScript is pretty awesome. It takes a lot of what makes JavaScript stupid and fixes it. It makes it a lot more like C#, which I’m a lot more comfortable in.
Promises
JavaScript has a single thread for its event loop, so if you have long running things (maybe going to get data from a server or something that would incur some latency), you want to use some kind of a callback. People with a lot more smarts than me have come up with ways to simplify the callback architecture, one of which is a Promise. The normal usage of a Promise in TypeScript goes like this:
The .then syntax is what to do when the long running thing is done. Anything inside of that lambda will be executed when the long running thing is done, but otherwise is ignored, allowing the single threaded event loop to continue on its way.
A Better Way
If you’re familiar with C#, then you’re probably familiar with the async/await architecture. It certainly simplifies writing asynchronous code. Well, TypeScript gives us a similar thing when working with Promises. In our above example, the async/awaited version would look like this:
It gets rid of the braces and the .then, and just makes everything cleaner. Obviously this is a contrived example, but its pretty easy to envision a scenario where multiple nested promises can lead to a maze of callbacks that make you want to tear your hair out. With async/await, its nice, clean, and readable.