暂停函数以等待 websocket 内的 ajax 请求

Pause function to wait for ajax request inside of a websocket

我有一个 WebSocket,可以在人们收到消息时将他们添加到消息列表中。我使用提取从服务器获取信息以构建消息列表,但我找不到让代码暂停直到提取完成的简单方法。我无法添加等待,因为函数位于非异步的 websocket 中。有人对此有什么建议吗?

        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;
            }
        });

实际上你可以在socket.on

中添加异步函数

socket.on('receive_message',async function(data) {