Reputation: 33
I am learning Node js and have hit a snag along the way. I am creating a rest endpoint for customer place order but before they place order I need to verify some payment from database which happens to be dumped by an external API. My problem is how to instruct my nodejs rest endpoint function not to wait forever for validation payment function and if I call the validation function if it has no data to wait a little bit and recall the same function again to check if data was dumped by external API but if it has elapsed 30 seconds of waiting I respond back to client time out. Here is my code.
controller.placeOrders = async function (req, res, callback)
{
/**
* I want to call this method and wait for 30 seconds
* if no respond I giver user response of time out
* but if the function has a message 'record found' before 30 seconds elapse it should
* respond to user immediately
*/
validateCustomerPayment(req.body.amount,req.body.contact,function (result) {
const code = result.startsWith("record found") ? 200 : 400;
res.status(200).json({
message: result,
code: code,
});
}
);
}
/**
*
* @param {type} req
* @param {type} res
* @param {type} callback
* @returns {undefined}
* this function is waiting for data from some external api
* so for data to be available for validation the external api must dump data here
* and dont want the placeOrders to wait forever
*/
service.validateCustomerPayment = async function (req, res, callback)//this is an exported function
{
Orders.find({PhoneNumber: customer_contact, flag: 'N'}).then((result)=>
{
if (result != null)
{
if (result.length >= 1)
{
callback("record found");
}
else{
callback("record not found");
}
}
}).catch(error=>{
callback("some error occurred");
});
}
Upvotes: 1
Views: 1200
Reputation: 191
Just use the "setTimeout" function for your need.
let myTimeout = setTimeout(testFunction, 30000);
function testFunction() {
console.log("Completed Successfully!");
}
This piece of code will wait 30 seconds and then execute the function 'testFunction'.
Upvotes: 0
Reputation: 285
If you use Node.js > 15 then you can use timersPromises.setTimeout
You'd do something like
import {pTimeout,} from 'timers/promises';
await pTimeout(30000)
pTimeout will return a promise.
Upvotes: 0