简体   繁体   中英

How do I get my function inside a map to return a value instead of a Promise pending?

I am using Node.js (I am at beginners level) and Google Cloud Firestore and I am having issues with having my map function to wait for my getStuff() -function, and will instead return a Promise rather than the value/text itself.

I have two functions like this:

function getUserData() {
   return db.collection('users').get()
        .then((querySnapshot) => {
            var docs = querySnapshot.docs.map(doc => [doc.data(), doc.id, getStuff(doc.id)])
            console.log(docs)
            return docs                          
        });
}

function getStuff(doc_id) {
   return db.collection('users').doc(doc_id).collection('tweets').limit(1).get()
        .then((querySnapshot) => {
            var docs = querySnapshot.docs.map(doc => doc.data());         
            console.log("TWEETS", doc_id, docs[0]['text']);
            return docs[0]['text']
        });   
}

The getStuff() function produces a console log result as:

TWEETS DAU86mxIhmD6qQQpH4F God’s country!
TWEETS JQHTO0jUjAodMQMR6wI I’m almost there Danny! 

whereas the console.log(docs) in getUserData() returns:

  [
    {
      name: "John McClane",
      twitter: 'john4'
    },
    'Yn4rEotMR02jEQSqdV4',
    Promise { <pending> } // <- This is where the tweet should have been
  ]

I am not to familiar with Promises and await/async and I can't get that to work. How do I set up my getUserData-function so that it will provide the Tweet text and not a Promise { pending }?

since getStuff() returns a promise you need to await it to resolve.

    async function getUserData() {
       return db.collection('users').get()
            .then((querySnapshot) => {
                var promises = querySnapshot.docs.map(async doc => {
                      var stuff = await getStuff(doc.id)
                      return [doc.data(), doc.id, stuff]
                })
               var docs =  await Promise.all(promises)
                console.log(docs)
                return docs                          
            });
    }

the getStuff() function returns a promise. one ways to resolve the promise is to use await.

Call the function using an await keyword. await keyword can be used only inside a async function so make the callback into a async function.

function getUserData() {
   return db.collection('users').get()
        .then( async (querySnapshot) => {
            var docs = querySnapshot.docs.map(doc => [doc.data(), doc.id, await getStuff(doc.id)])
            console.log(docs)
            return docs                          
        });
}

I haven't tested out my code, but it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM