Get async value from firestore

前端 未结 3 1181
无人及你
无人及你 2021-01-06 15:35

I am struggling with async operations. I am trying to simply get a value from firestore and storing it in a var.

I manage to receive the value, I can even save it in

3条回答
  •  一向
    一向 (楼主)
    2021-01-06 16:40

    You have things the wrong way around. It's much easier than you think it is.

    function getValues(collectionName, docName) {
        return db.collection(collectionName).doc(docName).get().then(function (doc) {
            if (doc.exists) return doc.data().text;
            return Promise.reject("No such document");
        }};
    }
    

    If a function returns a promise (like db.collection(...).doc(...).get()), return that promise. This is the "outer" return above.

    In the promise handler (inside the .then() callback), return a value to indicate success, or a rejected promise to indicate an error. This is the "inner" return above. Instead of returning a rejected promise, you can also throw an error if you want to.

    Now you have a promise-returning function. You can use it with .then() and .catch():

    getValues('configuration','helpMessage')
        .then(function (text) { console.log(text); })
        .catch(function (err) { console.log("ERROR:" err); });
    

    or await it inside an async function in a try/catch block, if you like that better:

    async function doSomething() {
        try {
            let text = await getValues('configuration','helpMessage');
            console.log(text);
        } catch {
            console.log("ERROR:" err);
        }
    }
    

    If you want to use async/await with your getValues() function, you can:

    async function getValues(collectionName, docName) {
        let doc = await db.collection(collectionName).doc(docName).get();
        if (doc.exists) return doc.data().text;
        throw new Error("No such document");
    }
    

提交回复
热议问题