简体   繁体   English

Promise.all 没有按预期工作 - Firebase

[英]Promise.all not working as expected - Firebase

I need promises.then () to be executed only after Promise.all is completed, however, firebase.database (), which should only be executed when the set of promises are resolved, is being executed first.我需要 promises.then () 仅在 Promise.all 完成后执行,但是,firebase.database () 应该只在承诺集解决后才执行,首先执行。

  const finalizarAlbum = async () => {
    setVisibleMod(false);
    if (nome && email && telefone) {
      const id = uuid();
      const promises = Promise.all(
        arrayPages.map((item, index) => {
          firebase
            .storage()
            .ref(id)
            .child(listaOrdemFotos[index])
            .putFile(item)
            .then((res) => {
              objetoPaginas.push({
                ordem: index,
                pagina: arrayPages[index],
                url: res.downloadURL,
              });

              setUnidade((unidade) => unidade + 1);
            })
            .catch((error) => setErro(erro));
        })
      );

      promises.then(() => {
        firebase
          .database()
          .ref('usuarios')
          .child(id)
          .set({
            nome,
            email,
            telefone,
            listaOrdemFotos: objetoPaginas,
          })
          .then(() => console.log('Enviado'))
          .catch((error) => setErro(erro));
      });
    }
  };

You are not returning anything from .map , so you're creating an array of undefined s, not an array of promises.您没有从.map返回任何内容,因此您正在创建一个undefined的数组,而不是一个承诺数组。 Change it to:将其更改为:

const promises = Promise.all(
  arrayPages.map((item, index) => {
    return firebase // <---------
      .storage()
      .ref(id)
      .child(listaOrdemFotos[index])
      .putFile(item)
      .then((res) => {
        objetoPaginas.push({
          ordem: index,
          pagina: arrayPages[index],
          url: res.downloadURL,
        });

        setUnidade((unidade) => unidade + 1);
      })
      .catch((error) => setErro(erro));
  })
);

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

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