如何从 hapi.js 路由处理程序外部回复

How to reply from outside of the hapi.js route handler

我有一个 hapi.js 路由,我想在其中延迟响应。我已经尝试存储 reply 函数并稍后调用它,或者将其包装在一个承诺中,但 hapi 总是立即响应 500 Internal Server Error 响应。

保存回复以备后用:

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

我已尝试创建回复承诺:

handler: function (request, reply) {
    var id = generateId();
    return new Promise(function (resolve, reject) {
        pendingReplies[id] = resolve;
    }).then(function (data) {
        return reply(data);
    });
}

我试过使用 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:

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 响应和以下输出:

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 是否可以从路由处理程序外部异步回复请求?

如果在您的处理程序中抛出错误,hapi.js 将立即退出并给出 500 状态代码。检查 generateId() 是否为有效函数。

您的代码的其余部分看起来适合您的第三个和第四个示例。 reply().hold() 需要在 handler returns.

之后保持连接打开

从版本 8 开始,Hapi 支持 Promised 响应,所以你可以这样做:

var respond = function(message) {
    return new Bluebird.Promise(function(resolve, reject) {
        setTimeout(() => {
            resolve(message);
        }, 2000);
    });
};

server.route({
    method: 'GET',
    path: '/',
    handler: function (request, reply) {
        reply(respond("Hello buddy"));
    }
});