【问题标题】:await used outside an async functionawait 在异步函数之外使用
【发布时间】:2021-11-09 13:10:25
【问题描述】:

我正在为一个项目开发 react + firestore 9,并且我一直在寻找一种检索数据以显示在我的应用程序上的方法。事情是我看到很多人推荐这种语法:

import firebase, { db } from 'path/to/firebase';
import {collection, getDocs, getDoc, query, doc,  addDoc, deleteDoc, updateDoc} from "firebase/firestore";

// CONSULTA
const result = await getDocs(query(collection(db, 'persons')));

我的问题是关于异步函数外部的等待,我总是遇到同样的错误,我通过创建一个异步函数来包装等待,如下所示:

import firebase, { db } from 'path/to/firebase';
import {collection, getDocs, getDoc, query, doc,  addDoc, deleteDoc, updateDoc} from "firebase/firestore";

// CONSULTA
const result = async() => { 
 const foo = await getDocs(query(collection(db, 'persons')));
};

所以;我可以做些什么让它在异步函数之外工作,还是我注定要永远将等待包装在异步函数中?

【问题讨论】:

    标签: javascript reactjs firebase asynchronous google-cloud-firestore


    【解决方案1】:

    如果我没记错的话,await 只能用在 async 函数中。但是你可以使用 .then(() => {}) 并在其中添加逻辑,你会确保在 promise 之后代码会被触发并且你的数据会被定义。

    在你的情况下,我猜你想要这样的东西

    getDocs(query(collection(db), 'persons')))
    .then((foo) => {
      // do something foo is defined
      // code outside this scope will be triggered before the .then 
    })
    .catch(err => console.log("there is an error", err));
    

    请记住,异步函数将始终返回一个承诺,因此即使您将代码包装在异步函数中,最后也必须使用 .then()。所以也许你想继续使用 .then,因为你不需要异步函数来使用 .then

    【讨论】:

    • 我还看到 .then 适用于异步函数。但是我不明白为什么每个人都推荐这种语法,如果你每次都需要添加 .then,你甚至可以在 firebase 官方文档上看到它,他们向你展示了这个 get 函数: const querySnapshot = await getDocs(collection(db , "用户")); querySnapshot.forEach((doc) => { console.log(${doc.id} => ${doc.data()}); });
    • @PedroMontesinosNavarro 正如我所说,异步函数无论如何都会返回一个 Promise,所以当您使用 await 它时,您的代码只会在 Promise 内同步,我们建议使用 .then() 因为它避免了这种混乱,也更容易使用工具进行调试。您可以使用 async await 但请记住,如果您想在此函数之后执行某些操作,则无论如何都必须添加 .then() 。 await 可以更好地阅读,因为您直接知道您正在等待某事
    • 我想我现在明白了,他们没有在这些代码示例中包含 .then() 以使代码更简洁,因此更容易理解,对吧?
    • @PedroMontesinosNavarro 是的,它使代码看起来是同步的,因此更易于阅读和解释。但是异步等待可能非常棘手;)
    猜你喜欢
    • 2017-02-02
    • 2021-03-05
    • 2022-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    相关资源
    最近更新 更多