DEV Community

Cover image for Asynchronism in JavaScript
Ernesto Herrera
Ernesto Herrera

Posted on • Updated on

Asynchronism in JavaScript

JavaScript is a popular programming language used in most modern websites and applications. One of its most important features is its ability to handle asynchronous tasks, which allows applications to multitask without blocking UI performance.

Asynchronisms in JavaScript rely on a feature called "running in the background." This means that while one task is running on the main JavaScript thread, other tasks can run in the background, allowing the application to continue running smoothly without interruption.

Callbacks

JavaScript's callbacks are functions that are passed as an argument to other functions and are executed when a certain event occurs or when an asynchronous operation is completed.

example of asynchronism
//callback
function printResult(result) {
  console.log(result)
}

function sumNumbers(myCallback,...nums) {
 let result = 0;
  for( let num of nums){
    result += num
 }
  myCallback(result);
}

sumNumbers(printResult,5,8,9);
Enter fullscreen mode Exit fullscreen mode

Promises

Promises allow us to handle asynchronous more easily in JavaScript by giving us a way to specify what actions to take when an asynchronous operation completes or fails. This allows us to write code that is easier to read and maintain, since we don't need to nest our code in a series of if and else blocks like in synchronous languages.

A promise can be in one of three states: pending, fulfilled, or rejected. When an asynchronous operation starts, a promise is created that is in the pending state. When the operation completes, the promise becomes fulfilled and the result of the operation is provided. If the operation fails, the promise is converted to rejected and a reason for failure is provided.

const requestPermission = new Promise((resolve, reject) => {
// We wait a second before resolving the promise
setTimeout(() => {
// We resolve the promise with the value "approve"
resolve("approve");
}, 1000);
});

console.log("Begin");

// Once the promise has been resolved, we print the resolve value to the console
requestPermission.then((resolve) => {
console.log(resolve);
});

console.log("finish");


Enter fullscreen mode Exit fullscreen mode

Async / Await

Another way to handle asynchronous tasks in JavaScript is by using the "async/await" method. This method allows you to write asynchronous code synchronously, making it more readable and easy to understand. To use the "async/await" method, you must mark a function as "async" and use the "await" keyword to wait for a promise to be fulfilled before continuing with code execution.

/// without  asycn await

const getNameAsync = () => {
// Wait 4 seconds before printing the value to the console
setTimeout(() => {
console.log("jose");
}, 4000);
};

// Declare the printNameAsync function as asynchronous
async function printNameAsync() {
console.log("calling");

// We execute the getNameAsync function and store the result in a variable
const message = getNameAsync();

// Print the value of the variable
console. log(message);
console.log("end");
}

// We execute the function
printNameAsync();
//calling
//undefined
//end
//jose
Enter fullscreen mode Exit fullscreen mode
// with asycn await

const getNameSync = () => {
return new Promise((resolve) => {
// We wait 4 seconds before resolving the promise
setTimeout(() => {
// We resolve the promise with the value "jose"
resolve("jose");
}, 4000);
});
};

// We declare the printNameSync function as asynchronous
async function printNameSync() {
console.log("calling");

// We wait for the promise returned by getNameSync to resolve
const message = await getNameSync();

// We print the resolution value of the promise
console.log(message);
console.log("end");
}

// We execute the function
printNameSync();
//calling
//jose
//end
Enter fullscreen mode Exit fullscreen mode

Asynchronisms in JavaScript are an indispensable feature that allows applications to handle multiple tasks at the same time without affecting the performance of the user interface. Knowing the different ways to handle asynchronous tasks in JavaScript is an essential skill for any modern web application developer.

Thank you very much for reading my article. I hope it has been of interest to you and that you have learned something new on the subject. I love writing about technology and programming, and I'm glad to share my knowledge and experiences.

If you have any questions or comments about the article, feel free to leave your comments, I would love to read your opinion.

Reference

Platzi Asincronismo
MDN

Top comments (0)