Reputation: 190
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
Upvotes: 1
Views: 101
Reputation: 5051
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
}
Upvotes: 1