Looking for a solution regarding a WebSocket that updates a messaged list when receiving a message. Currently using a fetch request to retrieve data from the server in order to populate the messaged list. However, facing an issue as the code needs to pause until the fetch request is completed. Unfortunately, adding await is not an option here since the function is within a websocket that is not async. Any suggestions on how to tackle this problem?
socket.on('receive_message', function(data) {
let messaged_user_li = document.getElementById('messaged_user_li'+data['from_user']);
console.log('messaged_user_li: '+messaged_user_li)
if (messaged_user_li == null) {
console.log('if fired')
//THIS is the fetch I want to pause the function until complete. Note that the await here does not work since the funciton isn't async.
await fetch('/get_messaged_user/'+from_user).then((response) => {
response.json().then((data2) => {
loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
});
});
messaged_user_li = document.getElementById('messaged_user_li'+data['from_user']);
}
console.log('messaged_user_li: '+messaged_user_li)
let message_user = document.getElementById('message_user'+data['from_user']);
let message_target = document.getElementById("message_target"+data['from_user']);
if (messaged_user_li.classList.contains('active') == false) {
messaged_user_li.classList.add('flash-message');
}
if (message_user != null) {
data = `
<li class="clearfix">
<div class="message-data text-right">
<span class="message-data-time">just now</span>
</div>
<div class="message other-message float-right">`+data['message']+`</div>
</li>`;
message_target.innerHTML += data;
//Move scroller to bottom when message received
myDiv = message_user.querySelector(".chat-history");
myDiv.scrollTop = myDiv.scrollHeight;
}
});