But wait, what is concurrency !?
I am glad you asked (Even if you didn't ask just pretend you did and we will move on 😉)
Concurrency means two or more processes running together in one thread but not at the same time, a lot of us have come across concurrency in Node JS but might not have noticed it (Prime example = me 😅).
You can run this code!!
The code in the example above must be familiar to most of us, but did you know this is a prime example of concurrency?. We all agree that line 7 is executed before line 5 right, Well that is concurrency!, multiple separate processes running in the same thread by taking turns to execute code.
These are the steps taken during execution.
fs.writeFile calls an underlying function which acts as a proxy between JS and C++
The function calls C++ code which creates a process on the event loop that will handle the write operation
console.log('Writing "Hello World!!" into file.txt')
The process writes content to
The process returns and our callback is executed
console.log('Wrote "Hello World!!" into file.txt')
This is great and all but there is one side effect to writing code with concurrent behavior and it is affectionately called the "Callback Hell"
Writing a file and then reading from it.
This gets exponentially worse the more you need to use data provided by such a function but the entire ordeal can be avoided when you use Promises.
The above code does not look that much better but with promises also come along the async/await keywords which will be extra helpful in cleaning up our code.
await keyword helps us retrieve data resolved by a promise as if it were directly returned from a synchronous function, but
await only works from within an asynchronous function and this is where the
async keyword comes in, it helps us define asynchronous functions where we can use
Now that is clean asynchronous code!!
Now that we can create promises and
await them, we no longer need to use callbacks. Here are some general examples.
Note: The default libraries in Node JS don't have great support for promises so we will be using third-party libraries for the async examples
Concurrency is a beautiful thing, especially in large scale applications where speed is a huge priority and I hope this post helped you learn a bit more about it and how best to apply it.