简体   繁体   English

如何使用 Async/Await 在 JavaScript 中异步运行两个函数;

[英]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 1.改变MedicineGroup函数

  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. 2.删除组函数。

  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然后一个最终的 function 用于调用上面的两个函数如下

  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 ie the changing medicine Group logic.问题如何使我的removeMedicinesFromGroup() function 异步,这样deleteGroup() function 仅在上面的代码完成时才被调用,changing medicine Group逻辑。 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.请帮忙。

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 .changeMedicineGroupFunctiondeleteGroup开始,两者都应返回 promise 以便在您的情况下在另一个 function 中等待它removeMedicinesFromGroup

Example of changeMedicineGroupFunction: 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:然后在 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.我使用常规 for Loop 而不是 forEach 在其中使用 await 。 I found this now that has many answers about using async/await in for loop whether sequence or parallel.我现在发现这个有很多关于在 for 循环中使用async/await的答案,无论是顺序还是并行。 Using async/await with a forEach loop . 将 async/await 与 forEach 循环一起使用

I hope it works for you.我希望这个对你有用。

You can invoke deleteGroup() after the code above it has completed by preceding the code above with await keyword.您可以在上面的代码完成后调用deleteGroup() ,方法是在上面的代码前面加上await关键字。

For example:例如:

await doSomethingBefore();
await alsoDoThisBefore();
// deleteGroup() is only invoked after the two awaited calls have completed
deleteGroup();

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. changeMedicineGroup 应该为每种药物返回一个 promise 并使用Promise.all()检查是否所有必需的组都已更改并发布删除该组。 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

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

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