Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delay a function call inside a express controller without hanging the API?

I'm learning to develop an ExpressJS API and I need to know how to delay the call of a function but to answer the client with a success code even if the process has not ended.

A simple code sample would be:

router.post('/', (req,res) => {
   if(req.body.success) {
      createRecord(req.body); // I need this function to be called after X minutes
   }
   return res.status(201).send(`Record will be created in X min from ${now}.`)
});

While searching I found the function setTimeout. However, is not clear to me how does it work.

  • The client needs to wait X minutes to receive my success message?
  • The function createRecord is called even if the function already returned an answer?
  • The API will still available for other calls in the X minutes period of time?

I hope someone could help me to clarify my doubts. Thanks.

like image 963
Xyleth Absol Avatar asked Jan 31 '26 17:01

Xyleth Absol


1 Answers

Step 1: Add a next to your function

It passes the context of your API call to another route handler. This enables you to pass the success message immediately and then do something else afterwards in your own time

router.post('/', (req,res, next) => {
    if(req.body.success) {
        return res.status(201).send(`Record will be created in X min from ${now}.`);
    }
    next(); // This sends the context of the original request to the next function underneath it.
});

Step 2: Function that promisifies the setTimeout function.

setTimeout is an async function so it will wait.

const waitHere = (time) => new Promise(resolve => setTimeout(resolve, time));

Step 2 - Option 1

router.use('/', async (req,res, next) => {
    if(req.body.success) {
        await waitHere(1000 * 60 *2); // 2 minute wait
        createRecord(req.body); 
    }
});

Step 2 - Option 2

There is no need for the async since you're not doing anything else in the second function handler.

router.use('/', (req,res) => {
    if(req.body.success) {
        setTimeout(() => {
            createRecord(req.body); 
        }, 1000 * 60 * 2);
    }
});

The API will still available for other calls in the X minutes period of time?

  • yes, each execution of the API is unique.
like image 71
Adrian Samuel Avatar answered Feb 03 '26 09:02

Adrian Samuel