我有一个定制的useMutation钩子:
  const {
    status: updateScheduleStatus,
    reset: updateScheduleReset,
    mutateAsync: updateSchedule,
  } = useUpdateSchedule(queryClient, jobId as string);但是如果我想做多个并行的突变,我会如何使用这个呢?
我尝试过实现以下内容,但突变在到达Promise.all(mutations行之前执行。
        let mutations: Array<any> = [];
        schedulesForDeletion.forEach(async (schedule) => {
          const resp = await monitoringService?.getSchedule(
            schedule.schedule_id,
          );
          mutations.push(
            updateSchedule({
              monitoringService: monitoringService as MonitoringServiceClient,
              schedule,
              etag: resp?.type === "data" ? resp.headers.etag : "",
            }),
          );
        });
        console.dir(mutations);
        await Promise.all(mutations);当mutateAsync返回一个不按顺序触发的Promise时,我会这样做,但似乎是这样的。
是否有一种在react-query中处理此问题的方法,或者我最好只使用axios执行此操作?在react-query中这样做是很有用的,因为当突变成功时,我需要使一些查询无效。
发布于 2022-01-19 14:27:20
并行运行多个突变确实适用于mutateAsync。
const { mutateAsync } = useMutation(num => Promise.resolve(num + 1))
const promise1 = mutateAsync(1)
const promise2 = mutateAsync(2)
await Promise.all([promise1, promise2])我猜在您的示例中,您向数组推送了一个承诺,然后继续循环和await monitoringService?.getSchedule。只有在它回来之后,你才能发射出第二个突变。
从这个意义上说,这似乎就是阻碍你执行死刑的原因。如果您推送来自getSchedule的最初承诺,它应该会工作:
schedulesForDeletion.forEach((schedule) => {
  mutations.push(
    monitoringService?.getSchedule(
      schedule.schedule_id,
      ).then(resp => updateSchedule({...})
    )
  )
})https://stackoverflow.com/questions/70771324
复制相似问题