Javascript 如何防止ForEach同时运行所有网络请求?
我正试着分批进行变异。当我使用for循环时,它工作得很好,但不是forEach循环,我不知道为什么 当我使用forEach时,它同时运行所有的Javascript 如何防止ForEach同时运行所有网络请求?,javascript,reactjs,Javascript,Reactjs,我正试着分批进行变异。当我使用for循环时,它工作得很好,但不是forEach循环,我不知道为什么 当我使用forEach时,它同时运行所有的updateAccount突变。我希望它运行批处理,等待结果,然后运行下一批处理。当我使用for循环而不是forEach循环时,它当前会这样做 batchIds是一个数组数组。每个嵌套数组最多包含10个ID,我试图同时运行一批最多10个突变。收到结果后,我想运行下一个10 以下是我的ForEach示例: const batchIds = [ [0,
updateAccount
突变。我希望它运行批处理,等待结果,然后运行下一批处理。当我使用for循环而不是forEach循环时,它当前会这样做
batchIds
是一个数组数组。每个嵌套数组最多包含10个ID,我试图同时运行一批最多10个突变。收到结果后,我想运行下一个10
以下是我的ForEach示例:
const batchIds = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13]
];
const handleSubmit = async () => {
try {
batchIds.forEach(async (batch, idx) => {
const results = await Promise.all(batch.map(accountId => {
return updateAccount({ accountId, tags, note });
}));
const idWithResult = results.map((result, index) => ({
id: accountIds[index],
didSucceed: result?.data?.pauseTrading.result.didSucceed
}));
setResponses(response => [...response, ...idWithResult]);
});
} catch (e) {
setError(e);
}
};
下面是我的For循环示例:
const batchIds = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13]
];
const handleSubmit = async () => {
try {
for (let i = 0; i < batchIds.length; i++) {
const results = await Promise.all(batchIds[i].map(accountId => {
return updateAccount({ accountId, tags, note });
}));
const idWithResult = results.map((result, index) => ({
id: accountIds[index],
didSucceed: result?.data?.updateAccount.result.didSucceed
}));
setResponses(response => [...response, ...idWithResult]);
}
} catch (e) {
setError(e);
}
};
const batchIds=[
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
[10, 11, 12, 13]
];
const handleSubmit=async()=>{
试一试{
for(设i=0;i{
返回updateAccount({accountId,tags,note});
}));
const idWithResult=results.map((结果,索引)=>({
id:AccountID[索引],
DidSuccess:result?.data?.updateAccount.result.DidSuccess
}));
设置响应(响应=>[…响应,…idWithResult]);
}
}捕获(e){
设置错误(e);
}
};
forEach
不“理解”返回承诺的函数(就像所有async
函数一样)。(更准确地说,它将简单地为每个数组元素逐个运行每个函数-它不知道“等待”每个回调返回的承诺来解析,任何wait
语法都不能改变这一点。)坚持for
循环。