【问题标题】:Unable to return a value from an async function using firestore无法使用 firestore 从异步函数返回值
【发布时间】:2020-06-17 00:10:59
【问题描述】:

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

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

我想读取 db,获取第一个匹配项并将其返回到 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();

【问题讨论】:

    标签: javascript node.js google-cloud-firestore


    【解决方案1】:

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

    首先,你的异步函数应该看起来更像这样:

    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的函数一样调用它:

    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 时,情况就大不相同了。我建议阅读更多关于它的工作原理。

    【讨论】:

    • try/catch 示例不起作用。为什么我需要使用.then?无效国家返回“无匹配文件”+“未定义”,而有效国家返回“未定义”?
    • 你需要使用 then 来从函数返回的 promise 中获取值,就像任何其他返回 promise 的函数一样。
    • 是的,但为什么不呢:let country = await getCountry();
    • 因为 country 将是一个 promise,而不是 promise 最终异步产生的值。我建议花一些时间来了解一下 Promise 在 JavaScript 中是如何工作的——这会经常出现。
    猜你喜欢
    • 2021-11-30
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2020-09-12
    相关资源
    最近更新 更多