DEV Community

Ebrahim Khalil
Ebrahim Khalil

Posted on

How to run a function in background?

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?

Top comments (3)

Collapse
 
jake_storma profile image
Jake Hall • Edited

Sooooo.... There are a few ways you can run a function in the background in order to avoid waiting for its response:

  1. Async/await: If you are using JavaScript, you can use the async/await pattern to run a function asynchronously. This allows you to write code that looks synchronous, but is actually asynchronous under the hood. To use async/await, you would declare your function as async, and then use the await keyword to pause the function until a promise is resolved. Here is an example:

async function checkNearbyUsers() {
const nearbyUsers = await checkUserLocation();
// do something with nearbyUsers
}

  1. 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);
    });
    });
    }

  2. 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 :)

Collapse
 
ekamid profile image
Ebrahim Khalil

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.

Collapse
 
prsaya profile image
Prasad Saya

Here is a place you can start with: Introducing asynchronous JavaScript @MDN.