Uso Promise.all para obtener 2 solicitudes. Pero Mi API tiene un límite de velocidad de una solicitud por segundo. Entonces hubo un error: el servidor respondió con un estado de 429 (Demasiadas solicitudes) ¿Hay alguna forma de resolver este problema?
const getKeywords = fetch('https://urlmyapi.com').then((res) => res.json().then((json) => { if (res.ok) { return json } throw json.message }) ) const getProducts = fetch('https://urlmyapi.com').then((res) => res.json().then((json) => { if (res.ok) { return json } throw json.message }) ) const [keywords, products] = await Promise.all([getKeywords, getProducts]) return { keywords, products, }Como se menciona en los comentarios, parece que desea usar setTimeout para esperar un segundo antes de ejecutar la segunda solicitud. Creo que esto funcionará.
async function getKeywords() { const res = await fetch("https://urlmyapi.com/keywords"); const json = await res.json(); if (res.ok) { return json; } throw new Error(json.message); } async function getProducts() { const res = await fetch("https://urlmyapi.com/products"); const json = await res.json(); if (res.ok) { return json; } throw new Error(json.message); } async function getKeywordsAndProducts() { // make first request const keywords = await getKeywords(); // pause for one second await new Promise((resolve) => setTimeout(resolve, 1000)); // make second request const products = await getProducts(); return { keywords, products }; }Oye, deberías usar la técnica de denuncia en este caso al retrasar tus llamadas a la API.
const getKeywords = fetch('https://urlmyapi.com').then((res) => res.json().then((json) => { if (res.ok) { return json } throw json.message }) ) const getProducts = fetch('https://urlmyapi.com').then((res) => res.json().then((json) => { if (res.ok) { return json } throw json.message }) ) const reolvePromisesWithDelay=async(promises=[],delay=3000)=>{ return Promise.all(promises.map((prom, index) => { if(index % 2){ return new Promise(resolve => setTimeout(resolve, delay)); }else{ return prom; } }); } const [keywords, products] = await reolvePromisesWithDelay([getKeywords, getProducts],4000) return { keywords, products, }Por lo tanto, no desea llamar a Promise.all en ese momento, porque activará todas las funciones simultáneamente. Mi sugerencia es simplemente disparar una llamada a la API, luego hacer una pausa por un segundo y disparar la segunda llamada a la API.
Algo como esto:
const keywords = await getKeywords(); await new Promise(resolve => setTimeout(resolve, 1000)); const products = await getProducts();