javascript - 在 useEffect React hook 中在不同时间实现多个 Firestore 调用
问题描述
useEffect(async() => {
await getWord();
const interval = setInterval(() =>{
time2 = time2 - 1;
if (time2 == 0) {
clearInterval(interval);
let dataURL = canvasRef.current.toDataURL();
const db = firebase.firestore();
db.collection("rooms").where("code", "==", code).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("rounds").where("round", "==", round).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("pictures").add({artist: name, dataURL: dataURL, votes: 0}).then(() => {
setVoteTime2(true);
});
});
});
});
});
}
}, 1000);
}, []);
上面的 useEffect 钩子出现错误。getWord是一个实现 firestore 调用的函数。错误是:“TypeError:n 不是函数”,它涉及发生在getWord中的 firestore 函数,以及在 time2 == 0 时发生的 firestore 调用。我怎样才能让两个异步调用都发生,显然是 firestore当 time2 == 0 时发生在getWord内部的调用发生在调用之前?如果需要更多信息,请告诉我!我只是不明白使用 await 不能解决这个问题。
解决方案
您不能在 useEffect 挂钩内将异步函数作为回调传递,因为它返回不允许的 Promise。只需尝试在 useEffect 中调用您的函数(但不要将回调函数定义为异步本身),然后在该函数内部执行您的异步任务......
useEffect(() => {
// call your function
myAsyncFunc(); <--- Here
async function myAsyncFunc () => {
await getWord();
const interval = setInterval(() =>{
time2 = time2 - 1;
if (time2 == 0) {
clearInterval(interval);
let dataURL = canvasRef.current.toDataURL();
const db = firebase.firestore();
db.collection("rooms").where("code", "==", code).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("rounds").where("round", "==", round).get().then((querySnapshot) => {
querySnapshot.docs.forEach((snapshot) => {
snapshot.ref.collection("pictures").add({artist: name, dataURL: dataURL, votes: 0}).then(() => {
setVoteTime2(true);
});
});
});
});
});
}
}, 1000);
}
}, []);
它的作用是使您免于返回 Promise,但仍允许您执行所有异步任务
推荐阅读
- apache-spark-sql - Spark SQL 中的检查点
- javascript - 如何在 WordPress REST API 中获取自定义字段发布对象数据
- go - 类型为 interface{} 时初始化 nil 指针
- tooltip - Oracle APEX 20.1 - 自定义字段帮助/工具提示
- google-apps-script - 使用 Google Apps 脚本查找特定值,然后在同一行中填充单元格
- regex - 正则表达式不匹配字符串中的确切单词
- java - 我在构建应用程序时在 android studio 中遇到了 Android 资源链接失败错误。我不知道如何解决这个问题。我是 Android Studio 的新手
- javascript - 仅当屏幕宽度> 1250px时如何执行脚本
- flutter - DropdownButtonFormField 导致 RenderFlex 溢出
- flutter - 如何在颤振中集成 facebook 登录?