如何等待多个 graphql 突变完成然后调用另一个函数
How to wait for multiple graphql mutations to finish then call another function
基本上我有一个对象数组,基于该数组的长度,我需要像这样为每个实例做一个突变:
arrayOfObjects.forEach((object) => {
someGraphQlMutation({
variables: object.id,
});
});
-----------------
const [someGraphQlMutation] = useMutation(
SOME_GRAPHQL_MUTATION,
{
onCompleted: (data) => {
// callback
}
}
);
但是,在完成所有突变之后,我需要调用另一个函数。在调用回调函数之前,我需要等待迭代突变完成。我可以在这种情况下使用 Promise.all
吗?
是的,您可以使用 Promise.all 等待所有突变:
const [someGraphQlMutation] = useMutation(SOME_GRAPHQL_MUTATION);
const doEverything = async () => {
try {
const results = await Promise.all(arrayOfObjects.map(object => {
return someGraphQlMutation({ variables: object.id });
}));
// results will be an array of execution result objects (i.e. { data, error })
// Do whatever here with the results
} catch (e) {
// Handle any errors as appropriate
}
}
基本上我有一个对象数组,基于该数组的长度,我需要像这样为每个实例做一个突变:
arrayOfObjects.forEach((object) => {
someGraphQlMutation({
variables: object.id,
});
});
-----------------
const [someGraphQlMutation] = useMutation(
SOME_GRAPHQL_MUTATION,
{
onCompleted: (data) => {
// callback
}
}
);
但是,在完成所有突变之后,我需要调用另一个函数。在调用回调函数之前,我需要等待迭代突变完成。我可以在这种情况下使用 Promise.all
吗?
是的,您可以使用 Promise.all 等待所有突变:
const [someGraphQlMutation] = useMutation(SOME_GRAPHQL_MUTATION);
const doEverything = async () => {
try {
const results = await Promise.all(arrayOfObjects.map(object => {
return someGraphQlMutation({ variables: object.id });
}));
// results will be an array of execution result objects (i.e. { data, error })
// Do whatever here with the results
} catch (e) {
// Handle any errors as appropriate
}
}