Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
Obtener datos paginados sin conocer el número de página

Tengo una API que solo permite obtener 1000 filas/obtener.

Entonces, por ejemplo, si quiero recuperar todos los datos de la API, la idea es recorrer los datos de respuesta cada vez que los obtenga y verifique su length (si responseData.length ! == 0, luego continúe buscando, deténgase cuando responseData.length === 0, también aumente firstRow cada vez que inicie el nuevo bucle hasta que llegue al final (responseData.length === 0)

 const fetchDataByRowCount = async (url, token, rowCount = 2, firstRow = 0) => { // firstRow is the value where the next fetch starts (Eg: 0-999, 1000-1999, etc.). // rowCount is the value for total rows fetched (Eg: 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; };

Pero el problema es que mi función no salió del bucle do while while, newResponse siempre devuelve valor !==0. Además, la función solo se ejecuta una vez.

¿Podrían ayudarme a verificar esto, por favor?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Del código que publicaste, todavía hay algo que no puedo descifrar, y es rowCount , así que lo dejo tal como está en el siguiente código "remasterizado":

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

Me deshice de algunas cosas que eran redundantes e hice que el código fuera un poco más eficiente con asignaciones de variables, etc.

También mencionas esto:

¡newResponse siempre devuelve valor! == 0.

Tenga cuidado al hacer esto, ya que newResponse inicialmente no está undefined . Ahora nunca usé bucles do...while while, así que no sé exactamente qué podría pasar, pero podría, por ejemplo, no ejecutarse en absoluto. Por lo tanto Also, the function only runs once si está hablando de la función paginatedFetch .

Ahora, si tuviera que reescribirlo, lo haría así:

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

Nuevamente, tenga cuidado con while (true) , debe estar absolutamente seguro de lo que devuelve la API y res es de hecho una array .

La mejor solución sería la API (si usted es el desarrollador) dando un punto final para contar el número total de filas. De esa manera, tendría una manera de estar absolutamente seguro de cuántas filas hay y escribir su código alrededor de eso.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda