NodeJS http:在返回之前等待请求侦听器中的另一个响应



基本上,它是一个web代理。在请求侦听器中,我创建另一个http请求,读取其响应并将其传递给响应。但我得等另一个请求结束。请参见下面的函数结构。

我已经搜索了现有的答案,但现有的答案是使用awaitPromise等,我认为,不适合我的结构。我想我需要c#的ManualResetEvent之类的东西。在发送请求(POS 1)之后,我需要将线程标记为阻塞,以便在完成响应(POS 3)之前可以阻塞它。当请求的响应结束时(POS 2),我需要标记线程继续。我如何在TypeScript/NodeJS中做到这一点?

function onRequest(req: http.IncomingMessage, res: http.ServerResponse)
{
....
if(arguments are valid)
{
... prepare options for request
try
{
const remoteReq = https.request(options, (remoteRes) =>
{
remoteRes.on('data', (d) =>
{
... pass it to the response.
});
remoteRes.on('end', (d) =>
{
//POS 2: resetevent.Set() allow thread to proceed
});
});
remoteReq.end();
//POS 1:resetevent.Reset() block thread
}
}
catch
{
}
}
else
{
}
//POS 3: resetevent.WaitOne() wait for the remote response to end.
res.end("");
}

不要"等待";在nodejs。您为事件注册一个侦听器,并在调用该侦听器时完成请求。您将res.end()res.write()移动到侦听器中,它告诉您已经完成或您有数据。Nodejs是一个非阻塞、事件驱动、异步I/O模型。你必须这样编程。

你没有展示足够的真实代码让我们写一些实际工作的东西,但一般的方案是这样的,你在你发送的http请求上监听data,enderror事件,你在这些事件处理程序中处理原始请求。在棒球比赛中没有哭泣。没有"等待"。在nodejs:

function onRequest(req: http.IncomingMessage, res: http.ServerResponse) {
....
if(arguments are valid) {
...prepare options
try {
const remoteReq = https.request(options, (remoteRes) => {
remoteRes.on('data', (d) => {
...pass it to the response.
res.write(...)
});
remoteRes.on('end', (d) => {
res.end(...);
});
});
remoteReq.on('error', err => {
console.log(err);
if (res.headersSent) {
// not much to do other than just hangup
res.end();
} else {
res.statusCode = 500;
res.end();
}
});
remoteReq.end();
} catch (e) {
// highly unlikely anything gets here because this is all
// asynchronous.  Instead, you need to listen for the 'error' event.
}
}
else {
// need to send some sort of response here, probably a 400 status
// if arguments are invalid
}
}

最新更新