1

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.

1
  • 1
    a) to use async/await, your changeMedicineGroup and deleteGroup functions must return the promises b) when using async/await, you cannot use .forEach() for looping Commented Jun 30, 2022 at 19:19

3 Answers 3

2

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((res) => res.text())

  };

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 whether sequence or parallel. Using async/await with a forEach loop.

I hope it works for you.

Sign up to request clarification or add additional context in comments.

3 Comments

You accidentally removed the res.text() from changeMedicineGroup, otherwise this is a good answer
Thanks @Zomitaka so what you are saying is that my function that i need to wait for must return a promise>
Exactly @AmohPrince and don't forget the other changes in removeMedicinesFromGroup. Yes @Bergi that's right i'll add it thank you.
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();

2 Comments

Why are you not waiting for deleteGroup() itself?
Because the question was only about invoking it after something has happened. Obviously the same applies regardless of function name.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.