我目前正在使用GraphQL HoC通过props传递一个突变。然而,我想同时运行一批突变,同时也有错误处理和知道哪些突变失败了-有能力再次运行失败的突变。我不知道我将运行多少个突变,这将取决于我获得的it的数量,这些it将作为一个数组在props中传递。
实现这一目标的最佳方法是什么?
我最初的想法是以某种方式在数组上使用Map方法,并在每个数组上运行变异。我不知道如何使用这种方法来跟踪失败的程序,我也不知道如何并行运行它们
突变将看起来像这样:
updateUserAccount({userId, reason})
我需要并行运行其中的5-10个
我将使用graphql HoC通过道具传递突变,这样我就可以访问我的组件中的突变。我想再运行两次失败的代码。
发布于 2021-04-20 06:40:00
使用Promise.all()调用突变。此外,您还需要创建一些mapper函数来控制某些请求失败时的尝试:
为每个请求创建和对象:
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();
});
};执行请求:
Run all function. You won't get any rejection, the mapper function is responsible for that. const run = () => {
Promise.all(meta.map(mapper)).then(response => {
console.log("Result:", response);
});
};
run();如果您需要知道哪个函数失败了,只需检查response对象:
const fails = response.filter(item => item.status === "ERROR");https://stackoverflow.com/questions/67100707
复制相似问题