繁体   English   中英

在 useEffect React hook 中在不同时间实现多个 Firestore 调用

[英]Implementing multiple Firestore calls at different times within useEffect React hook

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 调用的 function。 错误是:“TypeError:n 不是函数”,它涉及 getWord 中发生的 firestore function以及 time2 == 0 时发生的 firestore 调用。我怎样才能让两个异步调用都发生,显然是 firestore当 time2 == 0 时发生在getWord内部的调用发生在调用之前? 如果需要更多信息,请告诉我。 我只是不明白使用 await 不能解决这个问题。

您不能将异步 function 作为回调传递给 useEffect 挂钩,因为它返回 Promise 这是不允许的。 只需尝试在 useEffect 中调用您的 function (但不要将回调 function 定义为异步本身),然后在 function 内部执行您的异步任务...

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 但仍允许您执行所有异步任务

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM