1 回答

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
可以在這里找到
添加回答
舉報