Estoy tratando de obtener información de una base de datos, donde la información viene en varias páginas y todo debe compilarse en una sola matriz.
Sin embargo, a pesar de que estoy en un .then para manejar la promesa y llamo recursivamente a la función usando .then, todavía no espera y espera la matriz de "página siguiente" antes de que pueda tomarla.
A continuación se muestra el código correspondiente:
function getAllPersonEvents(jobID, pageNum) { getPersonEvents(jobID, pageNum).then(function(val){ if (val.length < 100) { console.log(val); console.log("above returned"); return val; } else { console.log("expecting return!"); let nextPages = getAllPersonEvents(jobID, pageNum + 1); console.log(nextPages); let allEvents = val.concat(nextPages); console.log(allEvents); return allEvents; } }); } function getPersonEvents(jobID, pageNum) { return fetch('WORKING FETCH URL' + pageNum + '&job_ids[]=' + jobID, options) .then(response => response.json()) .then(response => { return response.person_events; }) .catch(err => console.error(err)); }¿Cómo llego al mensaje "devuelto arriba"? código antes del "esperando retorno!" ¿parte?
Su getAllPersonEvents nunca devuelve nada. Su controlador then lo hace, pero no getAllPersonEvents . Para hacer lo que ha descrito, querrá devolver una promesa que se cumplirá con la matriz.
Siguiendo con sus devoluciones de llamada de promesa explícitas, puede hacerlo así (ver comentarios):
function getAllPersonEvents(jobID, pageNum) { // An array to build up our results in const all = []; // Get the initial events return getPersonEvents(jobID, pageNum).then((page) => { all.push(...page); if (page.length < 100) { // We have all of them, fulfill the promise with the full array return all; } else { // There may be more, recurse... return getAllPersonEvents(jobID, pageNum + 1).then((page) => { // ...and then add the results from the recursion to our // own, and fulfill this promise (which fulfills the main // one) with `all`. all.push(...page); return all; }); } }); } Sin embargo, es mucho más simple escribir usando async / await :
function getAllPersonEvents(jobID, pageNum) { const all = []; let page; do { page = await getPersonEvents(jobID, pageNum++); all.push(...page); } while (page.length >= 100); return all; }