You can not only pass parameterized callbacks or multiple callback functions with JavaScript. But, you can also pass asynchronous callback functions to other functions in JavaScript. This is particularly helpful when you want to perform an operation without knowing how long it’ll take to finish it. For instance, receiving some data from a remote server.
Example:
Let’s say you want to get some data for a user with User Id 1. You can pass this User Id to a function along with the callback function to get the data. The function will first assign a role for which we want the data and then call the remote API. To mimic the remote API call, I’m using a Promise with the setTimeout function. You’ll notice that there will be exactly 4 seconds delay before showing the response output.
const getRemoteServerResponse = (userId, userRole) => {
return new Promise((resolve) =>
setTimeout(() => {
resolve(`Data for User Id ${userId} (${userRole}) received!`)
}, 4000)
)
}
const useCallbackFunction = async (callback, userId) => {
const userRole = 'Admin'
console.log(
`Trying to receive data for User Id ${userId} having Role ${userRole}...`
)
const responseData = await callback(userId, userRole)
console.log(responseData)
}
useCallbackFunction(getRemoteServerResponse, 1)
Code language: JavaScript (javascript)
Here’s how the output should look like: