【问题标题】:How do I get my function inside a map to return a value instead of a Promise pending?如何让我的函数在地图中返回一个值而不是一个待处理的 Promise?
【发布时间】:2021-09-11 14:24:30
【问题描述】:

我正在使用 Node.js(我处于初学者级别)和 Google Cloud Firestore,我遇到了让我的地图函数等待我的 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) 返回:

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

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

【问题讨论】:

    标签: node.js google-cloud-firestore async-await promise


    【解决方案1】:

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

    【讨论】:

    • 这在逻辑上似乎完全正确,但是当我这样做时,我收到错误:“SyntaxError: await is only valid in async functions and the top level body of modules” for line "var docs = await Promise .all(承诺)”。只是通过反复试验,我已经看到这个错误经常出现。我该如何解决?
    • 我通过删除该行上的“await”来解决它。这行得通!谢谢!
    【解决方案2】:

    getStuff() 函数返回一个承诺。解决 promise 的一种方法是使用 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                          
            });
    }
    

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

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      相关资源
      最近更新 更多