Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

130
Visualizações
Using async when two requests have to be made and response from the first is needed in the other request

I have a async function like this:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;

    const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }

  next();
};

Here, response from the first request is required in the second request. But according to my knowledge since I am making asynchronous requests, the two requests should be made at the same time.

What I cannot understand:

  • So, how it is possible that there is no error occurring?
  • How is it that, sometimes the no document is added to Firestore? Like it is skipped somehow...
  • What modification can be done so that await addDoc(collection(db, "name_of_collec") executes compulsorily?

Context info:

  • I am using Express.js and Node.js to make a backend
  • I am using Axios to make the first request and the second one is adding a document to Firestore.
  • Firestore is a NoSQL database inside Google's Firebase.
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

But according to my knowledge since I am making asynchronous requests, the two requests should be made at the same time.

asynchronous doesn't mean that the requests are made at the same time. It means the code won't wait for the responses from these requests. Requests are made in the manner you add them in the code and responses will be asynchronous i.e the response will be received at some point in future time.

And there is no guarantee in what manner they will be received.

However, when you sue async/await, the code execution waits at await keyword for the response based on its success or failure it calls the next flow. It is nothing but syntactic sugar on promises. Under the hood, this is how your code will be executed:

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()l
  }

  axios.get(`https://a-domain.com/url/path`).then(result => result).then(data => {
      const info = data;
      
      addDoc(collection(db, "name_of_collec"), info).then(response => {
        console.log("Document written with ID: ", docRef.id);
      }).catch(e => {
        console.error(e);
      })
  }).catch(e => {
    console.error(e);
  })

   next();
};

So, how it is possible that there is no error occurring?

It is not necessary that the error occurs when you request. If that is the case catch handler should be activated.

How is it that, sometimes the no document is added to Firestore? Like it is skipped somehow...

The reason might be info is an empty object and firestore automatically removes the empty document.

There is no issue, but there is not data info that is empty sometimes that skips the addition(it does request firestore, but firestore removes the empty docs)

exports.myFunction = async (req, res, next) => {
  if (some condition) {
     next()
  }

  try {

    const results = await axios.get(`https://a-domain.com/url/path`);
    const info = results.data;
    const is_Info_Data = Array.isArray(info) ? info?.length >= 1: Object.keys(info) !== 0 
    if (is_Info_Data) {
      const docRef = await addDoc(collection(db, "name_of_collec"), info);
    console.log("Document written with ID: ", docRef.id);
    } else {
      console.log(`Info is empty ${info} no addition to DB`);
    }
    
    next();
  } catch (e) {
    console.error("Error adding document: ", e);
    next(e);
  }

};
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda