React 在一个循环中发送多个请求并等待



我正在向API发送多个请求,例如"myapi/id"。我的 ID 范围可能为 [0..10000]。因为一次发送所有 id 非常昂贵,所以我想发送切片等待它被获取,然后发送下一个切片。

这是我正在使用的代码:

async function getSlice(data) {
let promises = []
data.map((key) => {
promises.push(fetch("myapi/"+key)
.then(res => res.json())
.then((result) => console.log(result))) //I want to store the result in an array
}
await Promise.all(promises)
} 
function getAll(data) {
for(let i=0; i<= data.length; i+=10) {
getSlice(data.slice(i,i+10));
//I want to wait for the previous slice to complete before requesting for the next slice
}
}
getAll(ids)

但是,请求是异步发送的/没有等待发生。我想知道我的代码中是否存在错误/是否有任何方法可以使用 for 循环发送多个请求并等待它们完成,然后再发送下一个请求。

如果你想等待它,你需要在函数之前使用awaitasync完成

async function getAll(data) {
for(let i=0; i<= data.length; i+=10) {
await getSlice(data.slice(i,i+10));
}
}
getAll(ids).then(()=>console.log('all data processed')).catch(err=>/*handle 
error*/)

Ps. 我认为您需要使用 Promise.allSettled 方法而不是 Promise.all。如果您的请求之一将返回错误,则如果您使用 Promise.all,您将得到所有块失败。 Promise.allFixed将等待所有结果 - 正面或负面。 Anothe 旧解决方案是为每个请求使用 catch 方法,例如

promises.push(fetch("myapi/"+key)
.then(res => res.json())
.then((result) => console.log(result))
.catch((err)=>{/*handle error if needed*/; return null})

之后,您将在数组中出现一些带有结果的空值

一种有效的方法是始终保持被调用的请求(限制并行请求的最大数量),而不是您正在执行的方式。

通过使用你的方式(更容易),它将始终等待所有内容返回,然后检查数组中是否有更多数据,并再次递归调用该函数,或者在完成后返回所有内容。希望对您有所帮助。

async function getSlice(data) {
let promises = []
data.map((key) => {
promises.push(fetch("myapi/"+key)
.then(res => res.json())
.then((result) => console.log(result))) //I want to store the result in an array
}
await Promise.all(promises)
} 
function getAll(data, index=0, length=10) {
const allResponse = [];  
return getSlice(data.slice(index,q)).then(response => {
allResponse.push(response);
newLength = length + 11 > data.length ? data.length : length + 11;
if (index + 10 > data.length) //it's over
return allResponse;
return getAll(data, index + 10, length +11);
})}
Promise.all(getAll(ids).then(arrayResponse=>console.log('dowhatever',arrayResponse))

最新更新