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.
I hope someone could help me to clarify my doubts. Thanks.
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.
});
setTimeout function.setTimeout is an async function so it will wait.
const waitHere = (time) => new Promise(resolve => setTimeout(resolve, time));
router.use('/', async (req,res, next) => {
if(req.body.success) {
await waitHere(1000 * 60 *2); // 2 minute wait
createRecord(req.body);
}
});
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With