繁体   English   中英

无法使用 Firestore 从异步 function 返回值

[英]Unable to return a value from an async function using firestore

我是异步新手,正在尝试使用节点从 Firestore 数据库返回一个值。

该代码不会产生任何错误,也不会产生任何结果!

我想读取数据库,获取第一个匹配项并将其返回到 var 国家/地区。

const {Firestore} = require('@google-cloud/firestore');

const db = new Firestore();

async function getCountry() {
    let collectionRef = db.collection('groups');
    collectionRef.where('name', '==', 'Australia').get()
    .then(snapshot => {
    if (snapshot.empty) {
      console.log('No matching documents.');
      return "Hello World";
    } 

    const docRef = snapshot.docs[0];
    return docRef;
  })
  .catch(err => {
    console.log('Error getting documents', err);
  });
}


let country = getCountry();

当你声明一个 function async时,这意味着它总是返回一个 promise。 通常预计其中的代码将使用await来处理在 function 中生成的其他承诺。 最终返回的 promise 将解析为 function 返回的值。

首先,您的异步 function 应该看起来更像这样:

async function getCountry() {
    let collectionRef = db.collection('groups');
    const snapshot = await collectionRef.where('name', '==', 'Australia').get()
    if (snapshot.empty) {
        console.log('No matching documents.');
        // you might want to reconsider this value
        return "Hello World";
    } 
    else {
        return snapshot.docs[0];
    })
}

由于它返回 promise,因此您可以像任何其他返回 promise 的 function 一样调用它:

try {
    let country = await getCountry();
}
catch (error) {
    console.error(...)
}

如果您不能在调用 getCountry() 的上下文中使用 await,则必须正常处理它:

getCountry()
.then(country => {
    console.log(country);
})
.catch(error => {
    console.error(...)
})

当您注册使用 async/await 而不是 then/catch 时,情况就大不相同了。 我建议阅读更多关于它是如何工作的。

暂无
暂无

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

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