Today, we will explore concurrent or concurrency in JavaScript with this easy-to-understand guide.
Discover how to write code that can handle multiple tasks at the same time. And also to improve the performance of your applications.
Keep on reading to have a better understanding concerning JavaScript concurrency, along with examples.
What is concurrent o concurrency in JavaScript?
JavaScript concurrency refers to the ability of the language to handle multiple tasks at the same time.
As you may already be aware, JavaScript operates on a single thread.
Luckily, JavaScript provides three features that enable concurrent execution of code.
This is done using an asynchronous programming model with callbacks, Promises, or async/await.
Although JavaScript can only do one thing at a time because it is single-threaded, the event loop helps manage the order of instructions so that some tasks don’t block others.
In simple terms, concurrency in JavaScript allows it to handle multiple tasks simultaneously, even though it can only do one thing at a time.
Concurrency means that multiple computations are happening at the same time.
It’s a common aspect of modern programming that can be found everywhere, whether we like it or not.
For example, it can occur when multiple computers are connected in a network, when several applications are running on one computer, or when a computer has multiple processors (like multiple processor cores on a single chip).
What is an example of concurrent programming in JavaScript?
In JavaScript, there are three features available for executing code concurrently: Callbacks, Promises, and Async/Await.
Here are some examples of concurrent programming in JavaScript include:
Callbacks
Callbacks are functions that are executed asynchronously and are called back upon completion.
In the context of NodeJS, the main thread receives an event triggering the execution of the corresponding handler function.
After receiving an event, the handler assigns a task to be processed and begins executing it.
Meanwhile, the main thread promptly resumes listening for additional events.
For example:
function getData(callback) {
// Replicate the behavior of a slow network by simulating a network request with intentionally delayed response time.
setTimeout(() => {
callback({ data: "Hi, Welcome to Itsourcecode!"});
}, 1000);
}
getData((response) => {
console.log(response.data); // output: Hi, Welcome to Itsourcecode! after 1 second
});
Output:
Hi, Welcome to Itsourcecode!
Promises
Promises serve as placeholders for the eventual outcome of asynchronous operations, whether they succeed or fail. When a promise is created, it acts as a proxy for an unknown value.
This enables the creation of code statements that can handle the ultimate success value or failure reason of the promise.
For example:
function getData() {
return new Promise((resolve, reject) => {
// Replicate the behavior of a slow network by simulating a network request with intentionally delayed response time.
setTimeout(() => {
resolve({ data: "Hi, Welcome to Itsourcecode!"});
}, 1000);
});
}
getData().then((response) => {
console.log(response.data); // output: Hi, Welcome to Itsourcecode! after 1 second
});
Output:
Hi, Welcome to Itsourcecode!
A promise can exist in one of three states:
- Pending (pending)
This is the initial state, where the promise is neither fulfilled nor rejected. It indicates that the operation is still in progress.
- Fulfilled (fulfilled)
This state occurs when the operation is successfully completed.
- Rejected (rejected)
This state indicates that the operation has failed or encountered an error.
Async/Await
Async/await is a technique that lets you write asynchronous code in a way that looks and feels like regular synchronous code.
It builds on top of promises and makes writing and understanding asynchronous code easier.
For example:
async function getData() {
return new Promise((resolve, reject) => {
// Replicate the behavior of a slow network by simulating a network request with intentionally delayed response time.
setTimeout(() => {
resolve({ data: "Hi, Welcome to Itsourcecode!"});
}, 1000);
});
}
async function main() {
const response = await getData();
console.log(response.data); // output: Hi, Welcome to Itsourcecode! after 1 second
}
main();
Please note that the await keyword can only be used within async functions. If you attempt to use it outside of an async function, a SyntaxError will occur.
Output:
Hi, Welcome to Itsourcecode!
The async function() is a special type of function that works asynchronously and returns a Promise.
It behaves similarly to synchronous functions, making it easier to understand and use if you’re more comfortable with regular synchronous code.
Here’s an example of concurrency in JavaScript:
function downloadFile(url) {
return new Promise((resolve, reject) => {
console.log(`Starting download from ${url}`);
setTimeout(() => {
console.log(`Finished downloading from ${url}`);
resolve();
}, 3000);
});
}
async function processDownloads() {
const urls = ['http://sample.com/file1.txt', 'http://sample.com/file2.txt', 'http://sample.com/file3.txt'];
const downloadPromises = urls.map(downloadFile);
await Promise.all(downloadPromises);
console.log('All files have been downloaded');
}
processDownloads();
In this example, we have a function called downloadFile that pretends to download a file from a given website address.
It takes about 3 seconds to finish downloading. We also have a function called processDownloads that handles multiple downloads at once.
It starts downloading all the files together, without waiting for one to finish before starting the next.
Once all the downloads are done, a message saying “All files have been downloaded” is shown.
This example shows how JavaScript can handle many downloads happening at the same time using special functions called Promises and async/await.
Conclusion
In conclusion, this article provides a thorough explanation of concurrency in JavaScript and explores three features that enable the concurrent execution of code: callbacks, Promises, and async/await
It explains how JavaScript can handle multiple tasks simultaneously by leveraging the event loop, despite being single-threaded.
This article includes examples of concurrent programming in JavaScript using callbacks, Promises, and async/await, demonstrating how to write code that can handle multiple asynchronous operations efficiently.
Understanding the concurrency in JavaScript is essential for improving the performance of applications and optimizing their ability to handle concurrent tasks.
We are hoping that this article provides you with enough information that helps you understand the JavaScript concurrency.
You can also check out the following article:
- getInfo() method in JavaScript
- Fatal JavaScript invalid size error 169220804
- Create delete button in JavaScript
Thank you for reading itsourcecoders 😊.