【问题标题】:React firebase wait to then finish反应火力基地等待然后完成
【发布时间】:2021-06-20 14:27:11
【问题描述】:

您好,我使用 firestorage 保存图像,然后使用 if 发送带有 url 的信息,然后在条件之后获取 url,我知道 then 是一个承诺和异步,但我需要我的条件等待然后我不知道我的条件如何才能在函数内部等待然后完成?

 event.preventDefault();
let file = enterFileImage.imageFile;
imageUploader(file);

if (enterPhone.imageUrl != null) {
  const db = firebase.firestore();
  const docRef = db
    .collection("phones")
    .add({
      ...enterPhone,
    })
    .then((docRef) => {
      console.log("Document written with ID: ", docRef.id);
    });
}

图片上传器

const storageRef = firebase.storage().ref("/images");
const imageRef = storageRef.child(enterFileImage.imageName);
await imageRef.put(file).then((snapshot) => {
  snapshot.ref
    .getDownloadURL()
    .then((url) => {
      console.log(url)

      setPhone((Prevstate) => ({
        ...Prevstate,
        imageName: enterFileImage.imageName,
        imageUrl: url,
      }));
    })
    .catch((error) => {
      console.log(error);
      return false;
    });
});

【问题讨论】:

    标签: javascript reactjs firebase firebase-storage


    【解决方案1】:

    您需要将内部操作的结果“冒泡”到外部操作。您已经在 catch 中执行此操作,但还需要在您的 then 中执行此操作:

    await imageRef.put(file).then((snapshot) => {
      return snapshot.ref
        .getDownloadURL()
        .then((url) => {
          console.log(url)
    
          setPhone((Prevstate) => ({
            ...Prevstate,
            imageName: enterFileImage.imageName,
            imageUrl: url,
          }));
        })
        .catch((error) => {
          console.log(error);
          return false;
        });
    });
    

    通过从snapshot.ref.getDownloadURL() 返回结果,您的调用代码将等待文件上传并且确定其下载 URL。

    【讨论】:

    • 不起作用我在函数后面放了一个 console.log() 来查看是否保存 url,但它是一样的,在控制台中显示第一个钩子,1 o 2 秒后显示我需要的 url相反的顺序
    • 现在我把 await imageUploader() 和工作,但是钩子状态 enterPhone 更新太慢,检查 url 的条件仍然不起作用,如果我使用反应工具更新,但太慢
    • 我可以解决,使用 return all 并放入一个变量中
    • 很高兴听到 ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-17
    • 2020-08-26
    • 2022-11-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多