我目前正在使用 GraphQL HoC 通过 Prop 传递突变。然而,我想同时运行一批突变,同时也有错误处理并知道哪些突变失败了——能够再次运行失败的突变。我不知道我会运行多少突变,这取决于我获得的 ID 数量,这些 ID 将作为 Prop 中的数组传递下去。
实现此目标的最佳方法是什么?
我最初的想法是以某种方式在数组上使用 Map 方法并对每个数组运行突变。我不知道如何使用此方法跟踪哪些失败,我也不知道如何并行运行它们
突变看起来像这样:
updateUserAccount({userId, reason})
我需要并行运行其中的 5-10 个
我将使用 graphql HoC 通过 props 传递突变,这样我就可以访问我的组件中的突变。我想再运行失败的 2 次。
最佳答案
使用Promise.all()调用突变。您还需要创建一些映射器函数来控制某些请求失败时的尝试:
为每个请求创建和对象:
const ids = ["1", "2", "3"];
const meta = ids.map(id => ({
id,
fn: () => updateUserAccount({id, reason}), //--> mutation function
attemps: 0, //--> <= 3
status: null, //--> ["OK", "ERROR"]
data: null //-> response data, equal null if fails
}));
创建映射函数:
在这里您可以控制功能尝试。该请求将始终得到解决,这样您就不必担心被拒绝。如果请求在 3 次尝试后失败,您将使用数据等于 null 和状态等于错误来解析对象。
const mapper = item => {
return new Promise(async resolve => {
const call = async (attempts = 0) => {
try {
const data = await item.fn();
resolve({ ...item, status: "OK", attempts, data });
} catch (err) {
++attempts;
if (attempts < 3) {
call(attempts);
} else {
resolve({ ...item, status: "ERROR", attempts, data: null });
}
}
};
call();
});
};
执行请求:
运行所有功能。你不会得到任何拒绝,映射函数负责。const run = () => {
Promise.all(meta.map(mapper)).then(response => {
console.log("Result:", response);
});
};
run();
如果您需要知道哪个函数失败了,只需检查响应对象即可:
const fails = response.filter(item => item.status === "ERROR");
关于reactjs - 如何使用 Apollo Client 和 GraphQL HoC 并行运行多个突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67100707/