Nested function after nested function. Multiple redundant (but probably necessary) checks for errors.
Now imagine how great it would be if your code could look like this.
Soooo much easier to read… as if the code were entirely synchronous! I’ll take that any day, over the first example.
Using Async Functions
With async functions, that second code sample is incredibly close to what you can do. It only takes a few additional keywords to mark these function calls as async, and you’re golden.
Did you notice the difference, here?
With the addition of “async” to the outer function definition, you can now use the “await” keyword to call your other async functions.
This code does the same thing, has the same behavior from a functionality perspective. But visually, this code is significantly easier to read and understand.
The question now, is how do you create the async functions that save so much extra code and cruft, allowing you to write such simple workflow?
Writing Async Functions
Look at how the “createEmployee” function might be written, for example.
This code immediately creates and returns a promise. Once the work to create the employee is done, it then checks for some level of success and resolves the promise with the employee object. If there was a problem, it rejects the promise.
The only difference between this function and any other function where you might have returned a promise, is the use of the “async” keyword in the function definition.
Async With Flexibility
Beyond the simplicity of reading and understanding this code, there is one more giant benefit that needs to be stated.
With the use of promises in the the async functions, you have options for how you handle them. You are not required to “await” the result. You can still use the promise that is returned.
This code is just as valid as the previous code.
Yes, this code still calls the same async createEmployee function. But we’re able to take advantage of the promises that are returned when we want to.
And if you look back at the 3rd code sample above, you might remember that I was calling async functions but ultimately using a callback to return the result. Yet again, we see more flexibility.
Reevaluating My Stance On Promises
In the past, I’ve made some pretty strong statements about how I never look to promises as my first level of async code. I’m seriously reconsidering my position.
If the use of promises allows me to write such easily readable code, then I’m in.
Of course, now the challenge is getting support for this in the majority of browsers, as I’m not about to drop a ton of terrible pre-compiler hacks and 3rd party libraries into a browser to make this work for the web.
Node.js on the other hand? Well, it’s only a matter of time before v8.0 is stable for release.