[英]Typescript GraphQL Mutation - Iterate over arrays with objects
不幸的是,我没有长期使用 Typescript 和 GraphQL 组合。
我无法解决的问题是我有一个对象数组,我想对每个对象进行 GraphQL 突变。
数组如下所示:
(3) [{…}, {…}, {…}]
0: {__typename: 'user', id: '8', name: 'Tom', status: 'active', model: '11045779', …}
1: {__typename: 'user', id: '7', name: 'Mike', status: 'active', model: 'SIJY_B_3', …}
2: {__typename: 'user', id: '5', name: 'Peter', status: 'active', model: 'VS247HR', …}
我想对数组中的每个 object 执行以下 function :
async function updateUser(values: ValuesType) {
await updateUser({
variables: {
id: values.user.id,
status: "inactive",
},
});
}
对于单个对象,我可以毫无问题地使用 function,但不幸的是,我还没有找到一种方法来迭代数组。
答案可能很简单,但不知何故,我的尝试都没有成功。
是否有一个简单的解决方案来运行这个 function 与阵列中的每个 object?
Promise.all或Promise.allSettled是一次等待多个async
函数的惯用方法。 这些标准的 javascript 函数采用 Promise 数组并返回结果数组。
该模式适用于所有异步函数。 它不是 GraphQL 特定的。 这里的游乐场
// sample type
interface ValuesType {
id: String
name: String
status: String
model: String
}
// sample data
const updates: ValuesType[] = [{id: '8', name: 'Tom', status: 'active', model: '11045779'},
{id: '7', name: 'Mike', status: 'active', model: 'SIJY_B_3'},
{id: '5', name: 'Peter', status: 'active', model: 'VS247HR'}]
// a mock update function - with delay to simulate the GraphQL network call
async function updateUser(values: ValuesType): Promise<String> {
return new Promise<String>((resolve) => setTimeout(()=> resolve(values.id), 300))
}
// the important stuff - run the 3 mutations at once
(async ()=> {
// Option 1: Promise.all
const all = await Promise.all(updates.map(updateUser))
console.log('Promise.All result', all) // ["8", "7", "5"]
// Option 2: Promise.allSettled
const allSettled = await Promise.allSettled(updates.map(updateUser))
console.log('Promise.AllSettled result', allSettled) // [{"status": "fulfilled", "value": "8"} ...]
})()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.