Published
Asynchronous JavaScript refers to the use of asynchronous programming principles and techniques in JavaScript to handle tasks that may take some time to complete, so as not to block or wait for the task to complete before moving on to the next task. Asynchronous JavaScript uses constructs like Callbacks, Promises, and Async/Await to handle these 'lengthy' tasks efficiently.
A callback is a function passed into another function as an argument to be executed later. Callbacks can create complications as they can lead to heavily nested (or 'callback hell') code.
function fetchData(callback) { // Fetches data and calls the callback
...
}
fetchData(function(data) { // Callback function
console.log(data);
});
Promises are an improvement over callbacks in handling asynchronous operations, providing a more flexible way to handle asynchronous code by returning a promise to supply the value at some point in the future.
let promise = new Promise(function(resolve, reject) { // Promise creation
...
}).then(function(result) { // Resolve case
console.log(result);
}).catch(function(error) { // Reject case
console.log(error);
});
Async/Await, introduced in ES2017, is essentially syntactic sugar over promises, that makes asynchronous code look and behave more like synchronous code. It makes Promises easier and simpler to handle.
async function fetchData() { // Function declared as async
try {
let response = await fetch('https://...'); // Await fetch call
let data = await response.json(); // Await the response to be parsed
console.log(data);
} catch (error) { // Catch any errors
console.log(error);
}
}
fetchData();
The event loop is a key aspect of asynchronous JavaScript. It handles the execution of multiple chunks of your code, each when their time comes, all in a single thread. It maintains a queue of tasks and runs them one by one, without blocking the main execution flow.
By reading this article, you've invested 1.04 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.
JavaScript is a fun type of coding language that makes websites interactive. Imagine a website is like your favorite playground. JavaScript is like the slide, the swings, or the seesaw that make playing at the playground a lot more fun!
In real life, asynchronous is like doing chores while you wait for your cookies to bake! You don't have to watch the oven the entire time. When the cookies are ready, the timer will let you know. You can wash the dishes, clean your room, or color a picture while you wait!
In JavaScript, asynchronous works a lot like waiting for your cookies to bake. You give JavaScript a task to do (like baking the cookies), and while it's doing that, you can do other tasks (like coloring a picture). Then, when JavaScript is done with its job (the cookies are baked), it tells you, and you can do something with the result (eat the delicious cookies!).
Sometimes in JavaScript, we use something called 'Promises' for doing our tasks asynchronously. Imagine telling your friend you promise to give them a cookie once they're baked. Once the cookies finish baking, you keep your promise and give one to your friend. In JavaScript, when we ask it to do a task, it gives us a Promise, like saying: 'I promise to tell you when I finish this job!'. And when it's done, it keeps its promise!
const myPromise = new Promise((resolve, reject) => {
let cookiesBaked = bakeCookies();
if (cookiesBaked) {
resolve('Cookies are ready to eat!');
} else {
reject('Sorry, something went wrong baking the cookies.');
}
});
myPromise.then(message => {console.log(message);}).catch(errorMessage => {console.log(errorMessage);});
Imagine if we have two friends, and we promise to give our first baked cookie to the one who finishes their homework first. This is like 'Promise.race' in JavaScript. We have two Promises, and the one that does its job first gets to give back its result first.
let friendA = new Promise(resolve => setTimeout(resolve, 2000, 'Friend A'));
let friendB = new Promise(resolve => setTimeout(resolve, 1000, 'Friend B'));
Promise.race([friendA, friendB]).then(value => {
console.log(`The cookie goes to ${value}`);
});
By reading this article, you've invested 1.50 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.
For more detailed understanding of how JavaScript manages to be asynchronous and single-threaded at the same time, see this introduction to JavaScript's Event Loop
About author
Roman Y.
Senior Software Engineer at Nike
Certain articles only distributed to subscribers through email