Saurav
Saurav

Reputation: 29

How does node.js manage concurrency?

I am fairly new to nodejs? My question is how does nodejs handles concurrency exactly? I know that nodejs is single threaded and doesn't wait for requests to complete but does that mean we don't have any control in the order of events that occur?

Upvotes: 0

Views: 895

Answers (1)

nikhil.g777
nikhil.g777

Reputation: 904

Carrying out tasks in an asynchronous manner is one of the main strengths of NodeJS. Essentially, your program never stops and uses a single thread and performs operations asynchronously, thus the way you program in NodeJS will be quite different from traditional C/C++.

Most of the operations which need time to process, such as API calls will be implemented using callbacks, promises. As you start coding, you will understand and get used to it. If you need control over the order of events, especially in cases where the events are interdependent, async is a great package that offers various options to carry out tasks in a serial, parallel, auto, waterfall and many other ways ( You can refer to the documentation at : https://github.com/caolan/async )

Here's an example of performing operations serially using the async package :

async.series([
function(callback) {
    // Perform an API call
    callback(null, 'one');
},
function(callback) {
    // do some more stuff ...
    callback(null, 'two');
}
],
function(err, results) {
// reach here after the functions 1 and 2 are completed
});

Upvotes: 1

Related Questions