NodeJS supports async/await out of the box since version 7.6. I believe it has been the single greatest addition to JS since 2017. If you haven’t tried it yet, here are a bunch of reasons with examples why you should adopt it immediately and never look back.
[UPDATE]: This article has been edited to be more relevant in 2019
For those who have never heard of this topic before, here’s a quick intro
Assuming a function
getJSON that returns a promise, and that promise resolves with some JSON object. We just want to call it and log that JSON, then return
This is how you would implement it using promises
2. If you set a breakpoint inside a
.then block and use debug shortcuts like step-over, the debugger will not move to the the following
.then because it only “steps” through synchronous code.
With async/await you don’t need arrow functions as much, and you can step through await calls exactly as if they were normal synchronous calls.
Some valid skepticism you might have about using this feature is that it makes asynchronous code less obvious: Our eyes learned to spot asynchronous code whenever we see a callback or a
.then, it will take a few weeks for your eyes to adjust to the new signs, but C# had this feature for years and people who are familiar with it know it’s worth this minor, temporary inconvenience.
Follow me on twitter @imgaafar