conversation.user 和 conversation.secondUser 被追加到会话对象,但嵌套消息循环在响应发送到客户端后执行。
find: [
async (context) => {
await Promise.all(context.result.data.map((conversation) => {
return context.app.service('users').get(conversation.userId).then((data) => {
conversation.user = data;
return context.app.service('users').get(conversation.secondUserId).then((data) => {
conversation.secondUser = data;
return conversation.messages.map((message) => {
return context.app.service('users').get(message.userId).then((data) => {
console.log(data);
message.user = data;
});
});
});
});
}));
context.dispatch = context.result;
return context;
}
],
两件事:
- 您忘记了上一节中的
Promise.all
- 你没有充分利用
async/await
让你的生活更艰难
这应该有效:
find: [
async (context) => {
await Promise.all(context.result.data.map(async (conversation) => {
const data = await context.app.service('users').get(conversation.userId);
const secondData = await context.app.service('users').get(conversation.secondUserId);
conversation.user = data;
conversation.secondUser = secondData;
await Promise.all(conversation.messages.map(async (message) => {
const data = await context.app.service('users').get(message.userId);
console.log(data);
message.user = data;
}));
}));
context.dispatch = context.result;
return context;
}
]