如何使node-js端点等待30秒



我正在学习Node js,一路上遇到了一个障碍。我正在为客户下订单创建一个休息端点,但在他们下订单之前,我需要验证来自数据库的一些付款,而这些付款恰好被外部API转储。我的问题是如何指示我的nodejs rest端点函数不要永远等待验证付款函数,如果我在没有数据的情况下调用验证函数,请等待一段时间,然后再次调用同一个函数来检查数据是否被外部API转储,但如果等待了30秒,我会回复客户端超时。这是我的密码。

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");

});


}

如果使用Node.js>15然后您可以使用timersPromise.setTimeout

你会做一些类似的事情

import {pTimeout,} from 'timers/promises';
await pTimeout(30000)

pTimeout将返回一个promise。

只需使用;setTimeout";功能以满足您的需求。

let myTimeout = setTimeout(testFunction, 30000);
function testFunction() {
console.log("Completed Successfully!");
}

这段代码将等待30秒,然后执行函数"testFunction"。

最新更新