0

我有一个自定义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因为当突变成功时我需要使一些查询无效。

4

1 回答 1

2

并行运行多个突变确实适用于mutateAsync

const { mutateAsync } = useMutation(num => Promise.resolve(num + 1))

const promise1 = mutateAsync(1)
const promise2 = mutateAsync(2)

await Promise.all([promise1, promise2])

我猜在您的示例中,您将 Promise 推送到数组,然后继续循环并await monitoringService?.getSchedule. 只有在返回之后,您才会触发第二个突变。

所以从这个意义上说,这似乎是“阻止”你执行的原因。如果你推送来自 的原始 Promise getSchedule,它应该可以工作:

schedulesForDeletion.forEach((schedule) => {
  mutations.push(
    monitoringService?.getSchedule(
      schedule.schedule_id,
      ).then(resp => updateSchedule({...})
    )
  )
})
于 2022-01-19T14:27:20.017 回答