简体   繁体   English

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

[英]How to wait for multiple graphql mutations to finish then call another function

Basically I have an array of objects and based from that array's length, I need to do a mutation for each instance like so:基本上我有一个对象数组,基于该数组的长度,我需要像这样为每个实例做一个突变:

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

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

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

However, after all the mutations are done, I need to call another function. I need to wait for the iteration mutations to finish before calling the callback function. Am I able to use Promise.all in this context?但是,在完成所有突变后,我需要调用另一个 function。我需要等待迭代突变完成,然后再调用回调 function。我可以在这种情况下使用Promise.all吗?

Yes, you can use Promise.all to await all the mutations:是的,您可以使用 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
  }
}

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

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