I've been working with a websocket to fetch users.
I open the connection and send the messages to get the data, but if I want to return that user and use it elsewhere, I get undefined, but when running console.log inside the function, it gives me the user.
Here is my code :
export function fetchUser(id: number) {
const connection = generateConnection();
connection.onopen = () => {
connection.send(
JSON.stringify(
'{"msg":"connect","version":"1","support":["1","pre2","pre1"]}',
),
);
connection.send(
JSON.stringify(
`{"msg":"method","id":"1","method":"Users.getUser","params":[${id}]}`,
),
);
};
connection.on('message', async (event) => {
const data = event.toString();
if (data[0] == 'a') {
const a = JSON.parse(JSON.parse(data.substring(1))[0]);
if (a.msg == 'result') {
if ('error' in a) {
console.log(a.error.error);
connection.close();
return null;
} else {
let user= a.result;
console.log(user) // returns the user
return user; // return undefined
}
}
}
});
}
console.log(fetchUser(1));