Reputation: 11
I set up a project to return a value to app.js without it having to process the promise. This code returns undefined when I run it. Any Tips?
export.js `
const admin = require('firebase-admin')
const db = admin.firestore();
const ref = db.collection('Things')
async function getNameV(ting) {
return await ref.get().then(doc => {
doc.forEach(documentSnapshot => {
var data = documentSnapshot.data()
if (ting == data.name || ting == data.id) {
return data.name
}
})
})
};
module.exports.getName = function(ting) {
getNameV(ting).then(value =>{
console.log(value)
return value;
})
};
app.js
const exp = require('./export.js')
var name = await exp.getName('foo')
console.log(name)
Upvotes: 1
Views: 669
Reputation: 317372
Hugo is correct, but you have another error in addition to that. getNameV
isn't even returning a promise that yields the value your looking for. return data.name
is actually just returning from the anonymous function passed to forEach(). That value doesn't make it into the promise that you return from getNameV
. Right now, it is literally just returning a promise that contains undefined right now.
Also, return await [promise]
is redundant here. You can just return [promise]
, and not even both marking getNameV
with async
.
Upvotes: 0
Reputation: 4884
You have to return the promise created in your module.exports.getName
function, like this:
module.exports.getName = function(ting) {
return getNameV(ting).then(value =>{
console.log(value)
return value;
});
};
Then, on the app.js
side, you have to make sure you call the exported function from an async
function (otherwise you wouldn't be able to call it using await
):
const exp = require('./export.js')
async function start() {
var name = await exp.getName('foo')
console.log(name);
}
start();
Upvotes: 3