2 回答

TA貢獻2041條經驗 獲得超4個贊
如果你想等待它完成,你需要使用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})
之后,您將在數組中有一些帶有結果的空值

TA貢獻1818條經驗 獲得超8個贊
一種有效的做法是始終保持調用請求(限制并行請求的最大數量)而不是您正在執行的方式。
通過使用您的方式(更簡單),它將始終等待所有內容返回,然后檢查數組中是否有更多數據并再次遞歸調用該函數,或者如果完成則返回所有內容。希望能幫助到你。
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))
添加回答
舉報