How to chain asynchronous functions in JavaScript ?
Last Updated :
17 Jan, 2023
JavaScript is a single-threaded, asynchronous programming language. Thus, some time-consuming operations like I/O, accessing the database, network calls, etc. are performed asynchronously so that it does not interrupt things in the only JS thread. This can be done by asynchronous code like promises or async functions (which basically are cleaner promises). Asynchronous functions are cool, but the time of their execution is not certain, this sometimes creates a problem, when we have two async functions that depend on one another.
Note: This article will be using ES2015+ features like async functions, arrow functions, etc. However, the same result is achievable using older ES features.
Example 1:To help us with that we have three async functions (black-box functions).
JavaScript
<script>
async function getUserData() {
console.log('Fetching data');
}
async function cleanUserData(userData) {
console.log('Cleaning data');
}
async function saveToDataBase(userData) {
console.log('Saving to DB');
}
const userData = getUserData();
const cleanedData = cleanUserData(userData);
saveToDataBase(cleanedData);
</script>
Output: These are asynchronous functions and their execution time is not always the same. So these functions can run in any possible order. The following is one possible output.
Cleaning data
Saving to DB
Fetching data
There are two ways to run these functions and enforce an order of function executions.
1.Using Promise's .then()
JavaScript
<script>
async function getUserData() {
console.log('Fetching data');
}
async function cleanUserData(userData) {
console.log('Cleaning data');
}
async function saveToDataBase(userData) {
console.log('Saving to DB');
}
getUserData()
.then((userData) => cleanUserData(userData))
.then((cleanedData) => saveToDataBase(cleanedData))
.then(() => console.log('All work done'))
</script>
Output:
Fetching data
Cleaning data
Saving to DB
All work done
This is good and does the work, but sometimes it can create a callback hell, possibly ruining your mood when you see your code (just kidding).
2. Using async / await:
There is a cleaner way to do the same thing, waiting for a function to complete its execution using the await keyword. The await() works only inside the async() function. So, we need to wrap these inside a wrapper function.
JavaScript
<script>
async function getUserData() {
console.log('Fetching data');
}
async function cleanUserData(userData) {
console.log('Cleaning data');
}
async function saveToDataBase(userData) {
console.log('Saving to DB');
}
async function cleanAndSaveUserData() {
const userData = await getUserData();
const cleanedData = await cleanUserData(userData);
await saveToDataBase(cleanedData);
console.log('All work done');
}
cleanAndSaveUserData(); // does all the work
</script>
Output:
Fetching data
Cleaning data
Saving to DB
All work done
Note: This article does not cover error handling in chained async() functions for simplicity.
Similar Reads
How to create an Asynchronous function in Javascript? JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title
6 min read
JavaScript - How Does Asynchronous Code Work? Asynchronous code in JavaScript allows to execute code in the background without blocking the main thread. Asynchronous JavaScript is mainly used for handling tasks like network requests, file operations, and API calls. To understand how asynchronous code works, it's important to first know the conc
4 min read
How to Delay a Function Call in JavaScript ? Delaying a JavaScript function call involves executing a function after a certain amount of time has passed. This is commonly used in scenarios where you want to postpone the execution of a function, such as in animations, event handling, or asynchronous operations. Below are the methods to delay a
2 min read
How to convert an asynchronous function to return a promise in JavaScript ? In this article, we will learn how to convert an asynchronous function to return a promise in JavaScript. Approach:Â You need to first declare a simple function (either a normal function or an arrow function (which is preferred)). You need to create an asynchronous function and then further you need
3 min read
How to use await outside of an async function in JavaScript ? In this article, we will try to understand in what way or by how we may use await outside of an async function in JavaScript with the help of both theoretical explanations as well as coding examples. Let us first understand the following shown section in which all the syntaxes of declaring a promise
4 min read
How to execute a script asynchronously in HTML5 ? In this article, we will learn how to execute a script asynchronously on a webpage. This can be used in situations where loading the content is important as heavy scripts can cause the page to wait for it to load thereby making the page appear incomplete. Asynchronously loading would solve this issu
3 min read
JavaScript async function expression An async function expression is used to define an async function inside an expression in JavaScript. The async function is declared using the async keyword or the arrow syntax. Syntax: async function function_name (param1, param2, ..., paramN) { // Statements}Parameters: function_name: This paramete
2 min read
How To Return the Response From an Asynchronous Call in JavaScript? To return the response from an asynchronous call in JavaScript, it's important to understand how JavaScript handles asynchronous operations like fetching data, reading files, or executing time-based actions. JavaScript is a single-threaded nature means it can only handle one task at a time, but it u
3 min read
How to call a function that return another function in JavaScript ? The task is to call a function that returns another function with the help of JavaScript is called a Currying function, a function with numerous arguments that can be converted into a series of nesting functions with the help of the currying method. Approach:Define Outer Function:Create an outer fun
2 min read
How asynchronous JavaScript code gets executed in browser ? Functions or operations that are running in parallel with the other functions or operations are called the asynchronous functions or operations in JavaScript. Asynchronous functions use Callback Functions that get executed later. Let us see an example that demonstrates this: JavaScript setTimeout(fu
3 min read