如何等待多个graphql突变完成然后调用另一个函数

时间:2020-07-17 09:46:59

标签: javascript reactjs graphql graphql-mutation

基本上我有一个对象数组,根据该数组的长度,我需要为每个实例做一个变异,如下所示:

arrayOfObjects.forEach((object) => {
  someGraphQlMutation({
    variables: object.id,
  });
});

-----------------

const [someGraphQlMutation] = useMutation(
    SOME_GRAPHQL_MUTATION,
    {
        onCompleted: (data) => {
            // callback
        }
    }
);

但是,在完成所有突变之后,我需要调用另一个函数。在调用回调函数之前,我需要等待迭代突变完成。我可以在这种情况下使用Promise.all吗?

1 个答案:

答案 0 :(得分:1)

是的,您可以使用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
  }
}