javascript - 在异步函数外部使用await

标签 javascript reactjs firebase asynchronous google-cloud-firestore

我正在为一个项目开发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')));
};

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

最佳答案

如果我没记错的话,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));

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

关于javascript - 在异步函数外部使用await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69898745/

相关文章:

javascript - 如何在 Angular2 项目中将 moment.js 实现为管道

javascript - 如何在 Canvas 上更改 svg 颜色 - Fabricjs

javascript - MomentJS 有时会添加错误的小时数

reactjs - 如何在React JS中发生事件(单击按钮)时将一个组件替换为另一个组件

javascript - 从 web 应用程序中删除经过 firebase 身份验证的用户

firebase - Firebase仪表板看不到完整的服务器 key

javascript - httplib(python)可以与页面及其javascript交互吗?

reactjs - yarn 在创建 react 应用程序时出错

javascript - ReactJS:从 Contenteditable div 中删除除某些特定标签之外的所有 html 标签

javascript - 我可以使用 Firestore 获取使用 batch().set 创建的文档的生成 ID 吗?