1

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)
1
  • Meaningless, why you use .then when you have async/await? Commented Aug 12, 2018 at 3:05

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.