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

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

javascript 異步獲取函數

javascript 異步獲取函數

元芳怎么了 2022-12-22 15:14:47
我正在嘗試創建一個遞歸函數,它為給定數組的每個整數發送 PUT 請求,并在它的末尾調用另一個函數。function fetchArchive(arr,state,mailbox){  if(arr.length == 0){    load_mailbox(mailbox)  }  for(i of arr){    fetch(`/emails/${arr.shift()}`, {      method: 'PUT',      body: JSON.stringify({          archived: state      })    })    .then(fetchArchive(arr,state,mailbox))  }}但它似乎load_mailbox()在獲取數組的最后一項之前調用了該函數。我知道這應該使用async / await. 有人可以舉個例子來幫助我理解嗎?更新:事實證明下面的代碼正在運行async function fetchArchive(a,s,callback){  for(i of a){    await fetch(`/emails/${i}`, {      method: 'PUT',      body: JSON.stringify({          archived: s      })    })    // if i is the last item, load mailbox    .then(() => { if(i==a[a.length-1] && callback) callback()});  }}
查看完整描述

1 回答

?
GCT1015

TA貢獻1827條經驗 獲得超4個贊

這是異步 for..of 循環的正確代碼


async function fetchArchive(arr,state,mailbox){

    console.log(1)

  if(arr.length === 0){

    load_mailbox(mailbox)

  }

    

  for await (const elem of arr){

    await fetch2(elem);

        arr.shift();


        console.log({ elem })


    fetchArchive(arr,state,mailbox)

  }

}

但是,此代碼不起作用并導致無限遞歸 :) 我認為在迭代內改變數組是個壞主意。另外,請記住,then接收回調。因此,正確的論點then是:


.then(response=>fetchArchive(respone))

在你的情況下,你不能fetchArchive作為參數傳遞給then方法,因為fetchArchive不返回函數


[更新]


這是具有數組索引比較的工作代碼:


const fetchArchive = async (a, s, callback) => {

  for (const [index, value] of a.entries()) {

    await fetch(index)

      // if i is the last item, load mailbox

      .then(() => {

        if (index == a.length - 1 && callback) {

          callback();

        }

      });

  }

};

關于你的文檔entries可以在這里找到


查看完整回答
反對 回復 2022-12-22
  • 1 回答
  • 0 關注
  • 93 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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