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

180
Visualizações
How to run two functions asynchronously in JavaScript using Async/Await;

I am creating a simple react pharmacy application in which I'm supposed to change remove all the medicines from a certain group and then delete the group.

I have the two functions created like this.

1. changeMedicineGroupFunction

  const changeMedicineGroup = (medicineId, groupIdToChangeTo) => {
    fetch(
      `${process.env.REACT_APP_API_ROOT_URL}/changeMedicineGroup/${medicineId}/${groupIdToChangeTo}`,
      {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
      }
    )
      .then((res) => res.text())
      .then((response) => console.log(response));
  };

2.deleteGroupFunction.

  const deleteGroup = () => {
    fetch(`${process.env.REACT_APP_API_ROOT_URL}/deletegroup/${data.groupId}`, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.text())
      .then((response) => console.log(response));
  };

then a final function is used to invoke the two functions above as follows

  const removeMedicinesFromGroup = async () => {
    let unSetGroupId = 24;
    groupMedicines.forEach((medicine) =>
      changeMedicineGroup(medicine.medicineId, unSetGroupId)
    );
    deleteGroup();
  };

QUESTION How do I make my removeMedicinesFromGroup() function asynchronous in such a way that the deleteGroup() function is only invoked when the code above it is complete i.e the changing medicine Group logic. I want to use async-await. This is crucial for my application because if I delete a group while it still has data I have like whole foreign key constraint errors I'm trying to avoid.

Please Help.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can invoke deleteGroup() after the code above it has completed by preceding the code above with await keyword.

For example:

await doSomethingBefore();
await alsoDoThisBefore();
// deleteGroup() is only invoked after the two awaited calls have completed
deleteGroup();
about 4 years ago · Juan Pablo Isaza Relatório

0

In order to achieve that ,you have to some changes in your code. Starting with changeMedicineGroupFunction and deleteGroup that both should return a promise in order to await it in another function in your case removeMedicinesFromGroup.

Example of changeMedicineGroupFunction:

const changeMedicineGroup = (medicineId, groupIdToChangeTo) => {
    return fetch(
      `${process.env.REACT_APP_API_ROOT_URL}/changeMedicineGroup/${medicineId}/${groupIdToChangeTo}`,
      {
        method: "PATCH",
        headers: {
          "Content-Type": "application/json",
        },
      }
    )

  };

then in removeMedicinesFromGroup :

const removeMedicinesFromGroup = async () => {
    let unSetGroupId = 24;
    for(const medicin of groupMedicines){
     await changeMedicineGroup(medicine.medicineId, unSetGroupId)
    }
    await deleteGroup();
// you can use await here or let deleteGroup as it is without the behaviour you want will be achieved.
  };

And i used regular for Loop instead of forEach to use await in it. I found this now that has many answers about using async/await in for loop whather sequence or parallel. Using async/await with a forEach loop.

I hope it works for you.

about 4 years ago · Juan Pablo Isaza Relatório

0

changeMedicineGroup should return a promise for each medicine and use Promise.all() to check if all the required groups have been changed or not and post that remove the group. In case if any of those fails the group won't be deleted .

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

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