'Why is this returning some objects as promises? [duplicate]
I am making a messaging system on a website that I'm making. I'm trying to get the sender's name from a database. I have async/await and the result from my function where I get an object with each message ID and the sender's name is returning a promise. Here is my function:
async function getMessageSenders(){
let senders = {}
inbox.forEach(async (message) => {
if (message.sender === 'Baseball Stats') {
senders[message.id] = message.sender
} else {
senders[message.id] = await database.users.where('uid', '==', message.sender)
.get()
.then((q) => {
return q.docs.map((doc) => {
const data = doc.data()
return data.displayName
})
})
}
})
return senders
}
Solution 1:[1]
Because this expression senders[message.id] = await database.users.where('uid', '==', message.sender) assigns a promise actually, not a value. If you want to assign a value, you should put it in the .then() callback, like:
async function getMessageSenders(){
let senders = {}
inbox.forEach(async (message) => {
if (message.sender === 'Baseball Stats') {
senders[message.id] = message.sender
} else {
await database.users.where('uid', '==', message.sender)
.get()
.then((q) => {
const promises = q.docs.map((doc) => {
return doc.data()
})
Promises.all(promises).then(data => {
senders[message.id] = data.map(item => item.displayName)
})
})
}
})
return senders
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
