thejj
thejj

Reputation: 69

How to await a promise inside a firebase get request

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

Upvotes: 0

Views: 414

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 600090

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() {
    // 👇 Add return here
    return 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
    })
}

And the simpler version, getting rid of the extra code:

function getOwner() {
    return database.collection("users").doc(this.owner).get().then(doc => {
        return new User(doc.data().username, "", doc.data().email, [], doc.data().info)
    })
}

The top-level return is needed, because it allows the nested return to "bubble up" and back to the code that calls getOwner.

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317928

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

Upvotes: 2

Related Questions