gpt4 book ai didi

node.js - 尝试在 TypeScript 中添加监听事件

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:40 24 4
gpt4 key购买 nike

我正在尝试将监听器事件添加到我的 httpsServer,但我在传递正确的参数/类型时遇到了问题

this.httpsServer.listen(process.env.PORT || 3000);
this.httpsServer.on("error", onError);
this.httpsServer.on("listening", onListening(this.httpsServer));

export const onListening = (httpsServer: https.Server) => {
const addrress = httpsServer.address();
const bind = typeof addrress === "string"
? "pipe " + addrress
: "port " + addrress.port;
debug.info(`Listening on ${bind}`);
};

错误事件确实有效,但对于我得到的监听事件://“void”类型的参数不可分配给“(...args: any[]) => void”类型的参数

最佳答案

问题出在这一行:

this.httpsServer.on("listening", onListening(this.httpsServer));

您将 onListening(this.httpsServer) 的结果作为第二个参数传递给 on,但是 onListening 返回 无效

我想你的意思是这样的:

this.httpsServer.on("listening", () => onListening(this.httpsServer));

这会将一个函数传递给 on,每当收到 “listening” 事件时调用 onListening

您还可以从当前的 onListening 函数返回一个函数:

export const onListening = (httpsServer: https.Server) => () => {
const addrress = httpsServer.address();
const bind = typeof addrress === "string"
? "pipe " + addrress
: "port " + addrress.port;
debug.info(`Listening on ${bind}`);
}

关于node.js - 尝试在 TypeScript 中添加监听事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55541398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com