我正在為一個專案開發 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')));
我的問題是關于 async 函式外的 await,我總是遇到與我通過創建 async 函式來包裝 await 來解決的相同的錯誤,如下所示:
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')));
};
所以; 有什么我可以做的讓它在異步函式之外作業,還是我注定要永遠在異步函式中包裝等待?
uj5u.com熱心網友回復:
如果我沒記錯的話,await 只能用在 async 函式中。但是您可以使用 .then(() => {}) 并在其中添加邏輯,您將確保在承諾之后觸發代碼并且您的資料將被定義。
在你的情況下,我猜你想要這樣的東西
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/360684.html
標籤:javascript 反应 火力基地 异步 谷歌云firestore
上一篇:期待資料時的`WaitAll()`或`WhenAll`
下一篇:如何修復此單元測驗?
