Trying to build a more complex return of a MySQL query but the return doesn't wait for the forEach loop to complete.
export const Query = (query: string, values?: Array<string | number>) => {
return new Promise<Array<any>>((resolve, reject) => {
pool.query(query, values, (err, results) => {
if(err) reject(err);
return resolve(results);
});
});
};
const getUsersChats = async(userid: number) => {
let chats = await Query('SELECT * FROM users_chats u JOIN direct_chats d ON d.id = u.chatid WHERE u.userid = ?', [userid]);
//console.log(chats);
let buildReturn: any = [];
const build = async() => {
chats.forEach(async(chat) => {
let buildInnerObject = {};
let lastMsg = await Query('SELECT * FROM messages WHERE chatid = ? ORDER BY created DESC LIMIT 1', [chat.id]);
buildInnerObject = {...chat, lastMSG: lastMsg}
buildReturn.push(buildInnerObject);
});
}
await build();
console.log(buildReturn)
return buildReturn;
}
I'm looking for a return of something like:
{
id: 12,
userid: 28,
chatid: 12,
created: 2021-01-05T23:14:03.000Z,
userid_1: 28,
userid_2: 31,
title: 'Title',
lastMSG: [ [RowDataPacket] ]
},
{
id: 13,
userid: 28,
chatid: 13,
created: 2021-01-05T23:18:40.000Z,
userid_1: 28,
userid_2: 33,
title: 'Title'
lastMSG: []
}
]
but right now my return is []