问题描述
我有一条 hapi.js 路由,我想推迟响应.我试过存储reply
函数,以后再调用它,或将其包装在Promise中,但是hapi总是立即以500 Internal Server Error响应进行响应.
I have a hapi.js route where I want to defer the response. I've tried storing the reply
function and calling it later, or wrapping it in a promise, but hapi always responds immediately with a 500 Internal Server Error response.
存储答复以供以后使用:
Store the reply for later:
var pendingReplies = {};
server.route({
method: "POST",
path: "/",
handler: function (request, reply) {
var id = generateId();
pendingReplies[id] = reply;
}
});
... // reply later by calling:
function sendResponse(id, data) {
pendingReplies[id](data);
}
我尝试创建一个答覆的承诺:
I've tried creating a promise to reply:
handler: function (request, reply) {
var id = generateId();
return new Promise(function (resolve, reject) {
pendingReplies[id] = resolve;
}).then(function (data) {
return reply(data);
});
}
我尝试使用 reply().hold()
I've tried using reply().hold()
handler: function (request, reply) {
var id = generateId();
var response = reply().hold();
pendingReplies[id] = function (data) {
response.source = data;
response.send();
};
return response;
}
我尝试将reply().hold()
与Promise结合使用:
I've tried using reply().hold()
with a Promise:
handler: function (request, reply) {
var id = generateId();
var response = reply().hold();
return new Promise(function (resolve, reject) {
pendingReplies[id] = resolve;
}).then(function (data) {
response.source = data;
response.send();
return response;
});
}
使用这些命令中的每一个,一旦处理程序函数退出,我就会在节点控制台中得到500响应和以下输出:
With each of these, as soon as the handler function exits, I get a 500 response and the following output in the node console:
Debug: internal, implementation, error
Error: Uncaught error: socket hang up
at createHangUpError (_http_client.js:198:15)
at Socket.socketOnEnd (_http_client.js:283:23)
at emitNone (events.js:72:20)
at Socket.emit (events.js:163:7)
at _stream_readable.js:891:16
at process._tickDomainCallback (node.js:388:13)
hapi是否可以从路由处理程序外部异步回复请求?
Is it possible with hapi to reply to a request asynchronously from outside of the route handler?
推荐答案
如果处理程序中引发错误,则hapi.js
将立即退出并提供500
状态代码.检查generateId()
是否有效.
If an error is thrown within your handler, hapi.js
will immediately exit and give a 500
status code. Check if generateId()
is a valid function.
您的其余代码对您的第三个和第四个示例都是正确的. reply().hold()
对于在handler
返回后保持连接打开是必需的.
The rest of your code looks right for your third and fourth examples. reply().hold()
is necessary to keep the connection open after handler
returns.
这篇关于如何从hapi.js路由处理程序外部进行回复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!