I am trying to get the owner variable and since the function usually returns it as undefined I decided to use async/await but I can't use await within another function and I can access the variable outside of it. Is there an easy solution or do I have to rework the function?
async getOwner() {
database.collection("users").doc(this.owner).get().then(data => {
var owner = new Promise(function (resolve, reject) {
resolve(new User(data.data().username, "", data.data().email, [], data.data().info))
})
let result = await owner
return result
})
}
CodePudding user response:
If you're using async/await, there is almost never a need to use then()
or new Promise()
. You can write simply this, awaiting the promise returned by get()
:
async function getOwner() {
const snapshot = await database.collection("users").doc(this.owner).get()
const data = snapshot.data()
return new User(data.username, data.email, [], data.info)
}
You should probably also write code to check if there was any data in the snapshot and decide what to do if the document was not found as seen in the documentation.
You might want to review how async/await works in order to use it effectively.
https://javascript.info/async-await
CodePudding user response:
While Doug's answer is the better solution (hence my upvote on it), I wanted to point out why your current approach doesn't work, which is because you're not returning anything from the top-level code.
So if you want to not use await
, the closest to get your current code working would be:
function getOwner() {
//