Over the past three years, I’ve been learning JavaScript and some of its different flavors, frameworks, and libraries. The language is powerful, fun, and is backed by a large open-source community. As a full-stack JavaScript developer, you are truly limited only by your imagination.

Node.js is an asynchronous event-driven runtime for JavaScript. It lets you build highly scalable applications that have great performance. The secret sauce behind Node.js’s high performance is the fact that it goes against the common concurrency model used in other runtimes, frameworks, and languages.

All code in the Node.js process is executed in order from start to finish, however, the process has a single thread which means that it has a single call stack and memory heap. In short, if the thread is not free, code execution is delayed until it is. This is where developers need to exercise extra caution to avoid this performance bottleneck when building their applications. You should always follow a single rule: never block the main thread!

Blocking methods execute synchronously while non-blocking methods execute asynchronously. Blocking methods become dangerous when they consume the main thread and freeze up the entire process. As an example, consider the scenario of an API request made to a web server that takes 100ms to fulfill. Assume 90ms are needed to query a backend database through IO and 10 ms are needed to process and return data back to the client. By choosing non-blocking asynchronous query operations to the database, we can free up 90ms from the main thread which lets us do other things in the background (like process a second or third request) until the data for the first request is returned from the database.

Synchronous Loops

All developers are familiar with the traditional for loop:

for (var i=0; i < arr.length; i++) {
    var item = arr[i];
    // do something with item
}

This loop is simple, fast, and synchronous which means it will iterate over every element in the array from start to finish. Because of this, you should avoid having any long-running synchronous operations inside this loop because it will freeze up the main thread.

NOTE: A cleaner way of writing this exact same loop is by using the forEach method.

Want to read this story later? Save it in Journal.

arr.forEach((item) => {
    // do something with item
});

Asynchronous Loops

As part of ES7, Javascript  introduced the concept of async /await functions which allow developers to write asynchronous  code that looks and feels like synchronous  code. This is not a problem if the array does not need to be processed  sequentially.

#javascript #programming #software-development #computer-science #coding

Asynchronous Processing in JavaScript Loops
1.25 GEEK