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



我正在创建一个简单的react pharmacy应用程序,我应该在其中更改从某个组中删除所有药物,然后删除该组。

我像这样创建了两个函数。

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));
};

则使用最后一个函数调用上述两个函数,如下所示

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

如何使我的removeMedicinesFromGroup()函数异步,使deleteGroup()函数只在上面的代码完成时调用changing medicine Group逻辑。我想使用async-await。这对我的应用程序是至关重要的,因为如果我删除一个组,而它仍然有数据,我有像整个外键约束错误,我试图避免。

请帮助。

为了实现这一点,您必须对代码进行一些更改。从changeMedicineGroupFunctiondeleteGroup都应该返回一个承诺,以便在您的removeMedicinesFromGroup中等待另一个函数。

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 removeemedicinesfromgroup:

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.
};

我使用常规的for Loop而不是forEach来使用await。我发现现在有很多关于使用async/await在for循环是否顺序或并行的答案。使用async/await和forEach循环

我希望它对你有用。

您可以在上面的代码完成之后调用deleteGroup(),在上面的代码之前加上await关键字。

例如:

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

changeMedicineGroup应该返回每个药物的承诺,并使用Promise.all()检查所有所需的组是否已更改,并发布删除组。如果其中任何一个失败,该组将不会被删除。

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