0

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

这是我正在使用的代码:

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 循环发送多个请求并等待它们完成,然后再发送下一个请求。

4

2 回答 2

1

如果你想等待它完成,你需要使用awaitbefore函数async

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*/)

附言。我认为您需要使用 Promise.allSettled 方法而不是 Promise.all。如果您的一个请求将返回错误,如果您将使用 Promise.all,您将获得所有块失败。Promise.allSettled 将等待所有结果 - 正面或负面。另一个旧的解决方案是对每个请求使用 catch 方法,比如

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

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

于 2020-04-30T22:46:25.387 回答
1

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

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

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))
于 2020-04-30T23:31:57.337 回答