0

基本上我有一个对象数组,并且基于该数组的长度,我需要对每个实例进行突变,如下所示:

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

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

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

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

4

1 回答 1

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
  }
}
于 2020-07-17T11:14:26.543 回答