Rya*_*P13 11 javascript promise reactjs react-query promise.all
我有一个自定义useMutation钩子:
const {
status: updateScheduleStatus,
reset: updateScheduleReset,
mutateAsync: updateSchedule,
} = useUpdateSchedule(queryClient, jobId as string);
Run Code Online (Sandbox Code Playgroud)
据我所知,它设置了突变,但是如果我想做多个并行突变,我将如何使用它?
我尝试实现以下内容,但突变在到达线路之前执行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);
Run Code Online (Sandbox Code Playgroud)
我会通过mutateAsync返回 a来Promise表示它们不会按顺序开火,但似乎会按顺序开火。
有没有办法处理这个问题,react-query或者我最好用 axios 来执行这个操作?这样做会很有用,react-query因为我需要在突变成功时使某些查询无效。
TkD*_*odo 18
并行运行多个突变确实适用于mutateAsync:
const { mutateAsync } = useMutation(num => Promise.resolve(num + 1))
const promise1 = mutateAsync(1)
const promise2 = mutateAsync(2)
await Promise.all([promise1, promise2])
Run Code Online (Sandbox Code Playgroud)
我猜在你的例子中你将一个 Promise 推送到数组,然后你继续循环并await monitoringService?.getSchedule. 只有在它返回之后,你才会触发第二个突变。
所以从这个意义上说,这似乎就是“阻碍”你的执行的原因。如果你推送来自 的原始 Promise getSchedule,它应该可以工作:
schedulesForDeletion.forEach((schedule) => {
mutations.push(
monitoringService?.getSchedule(
schedule.schedule_id,
).then(resp => updateSchedule({...})
)
)
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19426 次 |
| 最近记录: |