Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

google cloud firestore - Node.js Value from Firebase not updating array in time for function call (even with Async Await)

I'm sure this issue is from my lack of async/await knowledge or general best practices in general. However, I cannot figure out what I am doing wrong. I'm looking to pull a value from my firestore database, include it into an array of "global variables" and then call it when ever I need it in other modules. However when I check the array pulled in the test function, it always returns a promise. The below code is an example of the last thing I tried.

index.js

const vars = require('./variables');

test();
async function test() {
  console.log('Expect database value', await vars.global()['lovePizza']);
}

variables.js (this is working, array updates)

const db = require('./database');

Let globalVars = {
  lovePiza : '',
}
const variables = {
  async global() {
    globalVars['lovePizza'] = (globalVars['lovePizza'] === '') ? db.getLovePizza() : globalVars['lovePizza'];

    return globalVars;
  }
}
module.exports = variables;

database.js (this is working, value gets pulled from db)

const database = {
  async getLovePizza() {
    const usersRef = db.collection('accounts').doc('user1');

    const doc = await usersRef.get();
    if (!doc.exists) {
      console.log('No such document!');
    } else {
      return doc.data()['lovePizza'];
    }
  }
}
module.exports = database;

Terminal Response:

Expect database value undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I saw a problem in your variables.js, I hope the problem is solved with these changes, use await before db.getLovePizza()

use try/catch when you use async/await

const db = require('./database');
Let globalVars = {
  lovePiza : '',
}
async global() {
  if(globalVars['lovePizza'] === ''){
      try {
       let result = await db.getLovePizza()//use await 
       console.log(result);
       globalVars['lovePizza'] = result
      } catch (error) {
        console.log(error)
        //do somthing for error handlig like throw 
      }
  }
  else{
    globalVars['lovePizza'] = globalVars['lovePizza'] //I think there is no need for this
  }
   return globalVars;
}

index.js

  test() {
  let result = await vars.global()
  console.log('Expect database value', result);// added to question
  console.log('Expect database value', result['lovePizza']);// added to question
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...