Estoy tratando de formar una matriz de URL para luego realizar búsquedas paralelas usando .map y Promise.all. El código en sí mismo funciona si lo intento con una matriz hecha manualmente, pero no si trato de formar una matriz (para paginación) con un en bucle. Obtengo el número máximo de páginas de los encabezados de la primera búsqueda y con ese número uso un ciclo for para agregar una página numerada creciente hasta la cantidad final de páginas.
Me estoy dando cuenta de que tratar de hacer un ejemplo mínimamente reproducible aquí de que esto no está 'funcionando' en cierto sentido, cuando hago esto en mi servidor con este código de muestra, funciona y
console.log(urls);en realidad muestra las URL en bucle y parece estar en formato de matriz, ya que usé push parece imposible no serlo. Pero, de nuevo, al realizar el urls.map no funciona en absoluto y al intentar hacer otra cosa, como .slice to urls, tampoco funciona, así que siento que no estoy formando la matriz, creo. ¿Soy? No puedo resolverlo.
async function smt() { var url = 'https://jsonplaceholder.typicode.com/todos/'; var urls = []; var firstFetch = fetch(url) .then(function(e) { var maxpages = 5; //var maxpages = e.get.headers('TotalPages'); < I would get the maxpages here for (let i = 1; i < maxpages; i++) { urls.push(url + i) } }); console.log(urls); var data = await Promise.all(urls.map(async url => { const res = await fetch(url); return res.json(); })) console.log(data); var other = [ 'https://jsonplaceholder.typicode.com/todos/1', 'https://jsonplaceholder.typicode.com/todos/2', 'https://jsonplaceholder.typicode.com/todos/3', 'https://jsonplaceholder.typicode.com/todos/4', ] var data2 = await Promise.all(other.map(async url => { const res = await fetch(url); return res.json(); })) console.log(data2); } smt();El problema fue con la función .then(). No tenía ni idea, pero probé cada parte hasta que funcionó.
async function smt() { var url = 'https://jsonplaceholder.typicode.com/todos/'; var urls = []; var firstFetch = await fetch(url) var maxpages = 5; //var maxpages = firstFetch.get.headers('TotalPages'); < I would get the maxpages here for (let i = 1; i < maxpages; i++) { urls.push(url + i) } console.log(urls); var data = await Promise.all(urls.map(async url => { const res = await fetch(url); return res.json(); })) console.log(data); var other = [ 'https://jsonplaceholder.typicode.com/todos/1', 'https://jsonplaceholder.typicode.com/todos/2', 'https://jsonplaceholder.typicode.com/todos/3', 'https://jsonplaceholder.typicode.com/todos/4', ] var data2 = await Promise.all(other.map(async url => { const res = await fetch(url); return res.json(); })) console.log(data2); } smt();/**** Respuesta actualizada ****/
async function smt() { var url = 'https://jsonplaceholder.typicode.com/todos/'; var urls = []; //var firstFetch = await fetch(url) < would get headers var maxpages = 5; //var maxpages = firstFetch.get.headers('TotalPages'); < I would get the maxpages here for (let i = 1; i < maxpages; i++) { urls.push(url + i) } console.log(urls); let promises = urls.map(async url => { let a = await fetch(url); return a.json() }) var data = await Promise.all(promises) console.log(data); } smt();Creo que este es un mejor enfoque ya que puede limitar la concurrencia cuando hace urls.map fuera de Promise.all.
Lo he hecho con p-limit en el nodo, funciona muy bien.
const limit = pLimit(8); let promises = urls.map(url => { return limit(async() => { let a = await fetch(url, optionsGet) return a.json() }) });