我有一個 API 只允許獲取 1000 行/獲取。
因此,例如,如果我想從 API 中檢索所有資料,則想法是每次獲取時回圈訪問回應資料并檢查length它(如果 responseData.length !== 0,則繼續獲取,當 responseData 時停止.length === 0,firstRow每次開始新回圈時也會增加直到它結束(responseData.length === 0)
const fetchDataByRowCount = async (url, token, rowCount = 2, firstRow = 0) => {
// firstRow is the value where the next fetch starts (E.g: 0-999, 1000-1999, etc.).
// rowCount is the value for total rows fetched (E.g: 1000 rows for each fetching time).
const data = await axios({
method: "get",
url: `${url}?rowCount=${rowCount}&firstRow=${firstRow}`,
headers: {
client_id: "",
Authorization: `Bearer ${token}`,
},
});
return data.data;
};
export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => {
let newResponse;
let total = [];
let token = await getToken(type); // stored to reuse token within an hour
do {
if (!token) {
const newToken = await getToken(type);
newResponse = await fetchDataByRowCount(url, newToken);
} else {
newResponse = await fetchDataByRowCount(
url,
token,
(rowCount = 2),
(firstRow = 0)
);
}
// console.log(total, "total");
total = [...total, ...newResponse];
// newResponse = [];
let newFirstRow = firstRow 1000;
newResponse = await fetchDataByRowCount(
url,
token,
(rowCount = 2),
newFirstRow
);
total = [...total, ...newResponse];
} while (newResponse.length !== 0);
return total;
};
但問題是我的函式沒有退出do while回圈,newResponse總是回傳值!==0。此外,該功能只運行一次。
請大家幫我檢查一下好嗎?
uj5u.com熱心網友回復:
從您發布的代碼中,我仍然無法弄清楚,它是rowCount,所以我讓它在以下“重新制作”的代碼中保持原樣:
export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => {
let newResponse;
let total = [];
let token;
let numberOfRows = firstRow;
do {
if (!token) token = await getToken(type);
newResponse = await fetchDataByRowCount(
url,
token,
(rowCount = 2),
numberOfRows
);
total = [...total, ...newResponse];
numberOfRows = 1000;
} while (newResponse.length !== 0);
return total;
};
我去掉了一些多余的東西,并通過變數賦值等使代碼更高效。
您還提到了這一點:
newResponse 總是回傳值!==0。
這樣做要小心,就像newResponse最初一樣undefined。現在我從未使用過do...while回圈,所以我不知道會發生什么,但它可能根本不運行。因此,Also, the function only runs once如果您在談論paginatedFetch功能。
現在,如果我要重新撰寫它,我會這樣做:
export const paginatedFetch = async (url, type, rowCount = 2, firstRow = 0) => {
let total = [];
let token;
let numberOfRows = firstRow;
while (true) {
if (!token) token = await getToken(type);
let res = await fetchDataByRowCount(
url,
token,
(rowCount = 2),
numberOfRows
);
total = [...total, ...res];
numberOfRows = 1000;
if (res.length <= 0) break;
}
return total;
};
Again, be careful with while (true), you have to be absolutely sure of what the API returns and res is indeed an array.
The better solution would be the API (if you are the developer) giving an endpoint to count the total number of rows. That way, you would have a way to be absolutely sure how many rows there are and write your code around that.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432261.html
標籤:javascript 节点.js api 循环 分页
上一篇:在回圈中覆寫“不存在的組件”
