nodejs异步等待不返回数组

时间:2020-01-30 06:55:38

标签: node.js google-cloud-firestore

我能够正确地console.log输出,但是当我尝试返回数组时,它失败了(即:无输出)


    //get all geo route
    app.get('/api/geo', function(req, res){
       res.send(getGeo());
    });

    async function getGeo() {
      let query = firestore.collection('geo'); //.where('foo', '==', 'bar');

      let response = await query.listDocuments().then(documentRefs => {
        return firestore.getAll(...documentRefs);
      }).then(documentSnapshots => {
         let geomatches = [];
         for (let documentSnapshot of documentSnapshots) {
            if (documentSnapshot.exists) {
              //console.log(`Found document with data: ${documentSnapshot.id}`);
              geomatches[documentSnapshot.id] = documentSnapshot.data();
            }//if
         }//for
         return geomatches;
      });

      return response;

    }

2 个答案:

答案 0 :(得分:1)

getGeo()async函数。您应该使用await来调用它。还要将您的路由回调声明为async

//get all geo route
app.get('/api/geo', async function(req, res){
   res.send(await getGeo());
});

答案 1 :(得分:1)

使用等待

  //get all geo route
   app.get('/api/geo', async function(req, res){
      res.send( await getGeo());
   });