Suppose I have a function that will run every time a user creates. The function will check if the user is nearby of other users. It's a long process, right? I don't wan to wait for its response. So I want to run this function in the background. How can I do that?
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (3)
Sooooo.... There are a few ways you can run a function in the background in order to avoid waiting for its response:
async function checkNearbyUsers() {
const nearbyUsers = await checkUserLocation();
// do something with nearbyUsers
}
Promises: Another option is to use promises to run your function asynchronously. A promise represents the result of an asynchronous operation, and allows you to attach callbacks to handle the success or failure of the operation. Here is an example using promises:
function checkNearbyUsers() {
return new Promise((resolve, reject) => {
checkUserLocation()
.then(nearbyUsers => {
// do something with nearbyUsers
resolve(nearbyUsers);
})
.catch(error => {
reject(error);
});
});
}
Web Workers: If you want to run your function in a separate thread, you can use web workers. Web workers allow you to run JavaScript code in the background, separate from the main thread. This can be useful for running long-running or resource-intensive tasks without blocking the UI. Here is an example using web workers:
`// In the main thread:
const worker = new Worker('worker.js');
worker.postMessage({ message: 'check nearby users' });
// In worker.js:
onmessage = function(event) {
if (event.data.message === 'check nearby users') {
checkUserLocation()
.then(nearbyUsers => {
// do something with nearbyUsers
postMessage(nearbyUsers);
})
.catch(error => {
postMessage(error);
});
}
};
`
Which option you choose will depend on your specific needs and the environment you are working in of course! Hopefully that helps :)
Okay. This is the scenario. If someone registers or updates their information a function will be invoked. That will fetch all users from the table, check each user's lat, long and activity radius, and update another table with ids of people under each radius (After a calculation). It's working fine with async/await on small amounts of data. But I think I need web workers. What do you think.
Here is a place you can start with: Introducing asynchronous JavaScript @MDN.