这是我的 socket.io 服务器代码,当我返回预期结果时,socket.emit() 函数可以正常工作,但是 Promise.all 函数会破坏输出。以下是该应用程序的日志
socket.on('hh:broadcast', (props, cb) => {
const session = sockets.get(socket);
if (!session) return;
const [room, that] = session;
const collaborators = sessions.get(room)!;
Promise.all<ArrayElement<NonNullable<Parameters<typeof cb>['0']>>>(collaborators
.filter(([, other]) => other !== that)
.map(([sock, other]) => sock
.emitWithAck('hh:data', { id: that, ...props })
.then(res => {
log.info("received", other, res);
return { id: other, ...res };
}))
).then(res => {
log.warn("Promise.all:", JSON.stringify(res))
cb(res);
});
});
日志显示了Promise.all的结果,但它不正确(只包含一个客户端的emit,而不包含其余的,它们只是空数组)这是为什么?我在 Promise 中返回了正确的结果,但是 Promise.all 无法将这些结果合并到数组中?
19:43:28.431 [WebSocket] received gDmNz9Ih2WWw {data: {data: [49, 237, 191, 23, 68, 120, 57, 163, 65, 57, 62, 200, 19, 155, 179, 23, 183, 242, 236, 97, 164, 99], type: "Buffer"}}
19:43:28.431 [WebSocket] received mX6SfA2F0MsD {data: {data: [49, 229, 183, 22, 72, 120, 202, 117, 249, 93, 17, 39, 226, 13, 101, 160, 208, 243, 76, 82, 95, 116], type: "Buffer"}}
19:43:28.431 [WARNING WebSocket] Promise.all: [{"id":"mX6SfA2F0MsD","data":{"type":"Buffer","data":[49,229,183,22,72,120,202,117,249,93,17,39,226,13,101,160,208,243,76,82,95,116]}},{"id":"gDmNz9Ih2WWw","data":{"type":"Buffer","data":[]}}]
首先,我认为您需要捕获所有错误以了解是否有任何连接失败。一旦数组中的任何一个 Promise 被拒绝,Promise.all 就会被拒绝,这很可能是你的情况。我认为其中一个 Promise 数组被拒绝,导致整个 Promise.all 提前拒绝。
.emitWithAck('hh:data', { id: that, ...props })
.then(res => {
log.info("received", other, res);
return { id: other, ...res };
})
.catch(error => {
log.error("Promise rejected for", other, error);
// return a default value or handle the error as needed
return { id: other, error: "An error occurred" };
})