reactjs - 如何使用 Apollo Client 和 GraphQL HoC 并行运行多个突变?
问题描述
我目前正在使用 GraphQL HoC 通过道具传递突变。但是,我想同时运行一批突变,同时还要进行错误处理并知道哪些突变失败了——能够再次运行失败的突变。我不知道我会运行多少个突变,这取决于我得到的 ID 的数量,这些 ID 将作为 props 中的数组传递。
实现这一目标的最佳方法是什么?
我最初的想法是在数组上以某种方式使用 Map 方法并在每个数组上运行突变。我不知道如何使用这种方法跟踪哪些失败,我也不知道如何并行运行它们
突变看起来像这样:
updateUserAccount({userId, reason})
我需要并行运行其中的 5-10 个
我将使用 graphql HoC 通过道具传递突变,这样我就可以访问我的组件中的突变。我想再运行两次失败的。
解决方案
使用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");
推荐阅读
- javascript - 2个方法里面有相同的循环,我怎样才能保持代码干燥而不重复两次?
- xaml - 在 XAML 命名空间中找不到类型
- javascript - 将 div 放在 svg 轨道上
- ios - CITemperatureAndTint 过滤器取值范围
- java - 可能的问题在哪里,我的应用程序崩溃,我试图从网站 thingsSpeak 检索传感器数据,我正在使用扩展片段
- vb.net - 当我尝试为我创建的类创建构造函数时,为什么会出现错误?
- ios - Xcode 10.0 错误:无法 IRGen 表达式,没有其他错误
- php - 从php中的数组计算总时间
- python-3.x - 在 aws lambda 中导入 python 模块
- json - 使用 Angular 2 在 json 文件中搜索