我正在嘗試從遠程 api 中獲取所有記錄,該 api 對一次可以獲取的數量有限制。我正在嘗試使用遞回,但是在 Python 中作業的總體思路我也無法在 JS 中作業。
這就是我目前正在做的事情,它將獲取 100 條記錄,但隨后會在后臺繼續運行。我嘗試了許多不同的方法來做到這一點,但似乎沒有任何效果。
任何幫助都會很棒,謝謝。
async getBooks(offset = 0) {
return await bookGenie.find(
'fiction',
100,
offset,
)
}
uj5u.com熱心網友回復:
我推薦這個:
async function getBooks(offset = 0, result = []) {
try {
// get new page
const page = await bookGenie.find(
'fiction',
100,
offset,
);
// add page to result array
result = result.concat(page);
// check is this the end
if (page.length !== 100) { // or what condition do you need
// return result array
return result;
} else {
// or increase offset and continue processing
return getBooks(offset 100, result);
}
} catch (err) {
throw err; // or handling somehow
}
}
現在遞回getBook回傳承諾,所有找到的記錄在決議時合并到一個陣列,并在拒絕時拋出錯誤。
所有請求將逐一執行,每一步增加 100 的偏移量,直到請求回傳少于 100 條記錄(不是整頁 = 串列結尾)。
用法:
const list = await getBooks();
console.log(list);
// [ ... ]
// List of all records
額外:相同的方法但緊湊
async function getBooks(offset = 0, result = []) {
try {
const page = await bookGenie.find('fiction', 100, offset);
return page.length !== 100 ? result.concat(page) : getBooks(offset 100, result.concat(page));
} catch (err) {
throw err; // or handling somehow
}
}
uj5u.com熱心網友回復:
您的await getBooks()電話:
getBooks((offset = offset = 100))
大概應該這樣寫:
getBooks((offset = 100))
之前的 if 陳述句在我看來是錯誤的。也許嘗試:
if (result.length < 1000) { // will continue until result.length is 1000
result.push(await getBooks(offset = 1)); /* 1 so the .push will add one element to the array each time. 100 may work too */
}
我無法實際測驗這個,但是這個(或類似的東西)對于 JS 來說更傳統。這是一個可以幫助您的鏈接https://www.javascripttutorial.net/javascript-recursive-function/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359904.html
標籤:javascript 接口 递归 异步等待
