亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

React 循環發送多個請求并等待

React 循環發送多個請求并等待

當年話下 2022-07-21 20:53:39
我正在向 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 循環發送多個請求并等待它們完成,然后再發送下一個請求。
查看完整描述

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})

之后,您將在數組中有一些帶有結果的空值


查看完整回答
反對 回復 2022-07-21
?
弒天下

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


查看完整回答
反對 回復 2022-07-21
  • 2 回答
  • 0 關注
  • 241 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號