繁体   English   中英

如何让我的函数在地图中返回一个值而不是一个 Promise 挂起?

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

我正在使用 Node.js(我处于初学者级别)和 Google Cloud Firestore,我在让我的 map 函数等待我的getStuff()函数时遇到问题,而是返回一个 Promise 而不是值/文本本身.

我有两个这样的功能:

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']
        });   
}

getStuff()函数生成控制台日志结果如下:

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

getUserData()console.log(docs) getUserData()返回:

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

我不熟悉 Promises 和 await/async,我无法让它发挥作用。 如何设置我的 getUserData 函数,以便它提供 Tweet 文本而不是 Promise { pending }?

由于getStuff()返回一个承诺,您需要等待它来解决。

    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                          
            });
    }

getStuff()函数返回一个承诺。 解决承诺的一种方法是使用 await。

使用await关键字调用该函数。 await关键字只能在async函数中使用,因此将回调函数设为async函数。

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                          
        });
}

我还没有测试过我的代码,但它应该可以工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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