0

I am unable to understand how I can access elements from an array in an asynchronous fashion. I have looked at

Async functions in for loops javascript

and

Using async/await with a forEach loop

but to no avail.

My functions

export async function processUserAllMessages() {
    let messages =  await getAllMessagesByRoom();
    var message;
    for (let message_obj of messages) {
        message = message_obj.data;
        let message_ref = message_obj.ref['@ref'].id;
        if (message.to == get(user).username) {
            if (message.acknowledged) {
                await deleteMessage(message_obj);
            } else {
                let promise = await processMessage(message_obj);
                console.log(message_ref)
            }
        }
    }
    return true;
}



async function processMessage(message_obj) {
    // code to process message
    return promise

Typical output

340877637764252236 
340877637764252236 
340877637764252236 
340877637912101449 
340877637912101449 
340877637912101449
340877637916295753 
340877637916295753 
340877637916295753

The messages are returned in the for loop multiple times. How can I fix this?

Psionman
  • 3,084
  • 1
  • 32
  • 65
  • It's not entirely clear what you are asking. If you `await` a Promise (which you do at `await processMessage(message_obj)` then that promise is awaited and the resulting value is returned, so your `promise` inside of the loop isn't a promise, but the value that the promise resolved to. – Ivar Aug 24 '22 at 13:01
  • `let promise = await processMessage` Yes, promise will no longer be a promise, that is the whole point of `await` to get the resolved value. It's a little unclear what problem your trying to solve here.. :( – Keith Aug 24 '22 at 13:03
  • @ivar The messages are returned in the for loop multiple times – Psionman Aug 24 '22 at 13:24
  • @Psionman Then either `messages` contains repeated messages, or the `// code to process message` isn't working correctly. Neither of which you have shown, so we can't really help you there. – Ivar Aug 24 '22 at 13:29
  • Please read [ask] and provide a [mcve]. We can't tell why `getAllMessagesByRoom` returns duplicate messages. – Quentin Aug 24 '22 at 13:29
  • In other words, your code looks fine, and the problem must be elsewhere that's not obvious from what you shared. – Evert Aug 24 '22 at 20:49
  • Thanks. I'll try to reproduce and post a better example – Psionman Aug 24 '22 at 22:00

0 Answers0