así que estoy aprendiendo sobre async-await en javascript y cuando trato de hacer este infierno de devolución de llamada (sé que no es la mejor práctica, pero tengo que aprenderlo) la segunda vez que llamo a la función, sigue llamándose a sí misma (bucle infinito ) puedes ejecutar el código para entender más porque nada me parece mal. Pasé los últimos 2 días tratando de entender el problema, pero terminé aquí.
código:
const xhr = new XMLHttpRequest(); const url = new URL("https://www.breakingbadapi.com/api/quotes"); const moveiData = (link, callBack) => { xhr.addEventListener("readystatechange", () => { if (xhr.readyState === 4 && xhr.status == 200) { } else if (xhr.readyState === 4) { callBack("could not fetch data"); } }); xhr.open("GET", link); xhr.send(); }; moveiData(url, (response) => { console.log(response); moveiData(url, (response) => { console.log(response); }); });No reutilice el mismo objeto XMLHttpRequest . Declare una nueva cada vez que llame a la función y asegúrese de devolver algunos datos en la devolución de llamada si hay una respuesta positiva.
const url = new URL('https://www.breakingbadapi.com/api/quotes'); const moveiData = (link, callBack) => { const xhr = new XMLHttpRequest(); xhr.addEventListener('readystatechange', () => { if (xhr.readyState === 4 && xhr.status == 200) { callBack(JSON.parse(xhr.response)); } else if (xhr.readyState === 4) { callBack('could not fetch data'); } }); xhr.open("GET", link); xhr.send(); }; moveiData(url, function (response) { console.log(response); moveiData(url, function (response) { console.log(response); }); }); Puede encontrar la relativamente nueva API fetch y el proceso async/await un poco más gratificantes .
const url = 'https://www.breakingbadapi.com/api/quotes'; function getData(url) { return fetch(url); } async function main() { try { const res = await getData(url); console.log(await res.json()); } catch (err) { console.log(err); } } main();Tienes tres opciones en ese tema.
1- Ha agregado un nuevo detector de eventos y debe eliminarlo cuando responda.
const xhr = new XMLHttpRequest(); const url = new URL("https://www.breakingbadapi.com/api/quotes"); const moveiData = (link, callBack) => { const handler = () => { if (xhr.readyState === 4 && xhr.status == 200) { xhr.removeEventListener("readystatechange", handler); callBack(JSON.parse(xhr.response)); } else if (xhr.readyState === 4) { callBack("could not fetch data"); } }; const a = xhr.addEventListener("readystatechange", handler); xhr.open("GET", link); xhr.send(); }; moveiData(url, (response) => { console.log(response); moveiData(url, (response) => { console.log(response); }); });2- Utilice la devolución de llamada onreadystatechange.
const xhr = new XMLHttpRequest(); const url = new URL("https://www.breakingbadapi.com/api/quotes"); const moveiData = (link, callBack) => { xhr.onreadystatechange = () => { if (xhr.readyState === 4 && xhr.status == 200) { callBack(JSON.parse(xhr.response)); } else if (xhr.readyState === 4) { callBack("could not fetch data"); } }; xhr.open("GET", link); xhr.send(); }; moveiData(url, (response) => { console.log(response); moveiData(url, (response) => { console.log(response); }); });3- Declarar nuevo XMLHttpRequest para cada función.
const url = new URL('https://www.breakingbadapi.com/api/quotes'); const moveiData = (link, callBack) => { const xhr = new XMLHttpRequest(); xhr.addEventListener('readystatechange', () => { if (xhr.readyState === 4 && xhr.status == 200) { callBack(JSON.parse(xhr.response)); } else if (xhr.readyState === 4) { callBack('could not fetch data'); } }); xhr.open("GET", link); xhr.send(); }; moveiData(url, function (response) { console.log(response); moveiData(url, function (response) { console.log(response); }); });const url = new URL("https://www.breakingbadapi.com/api/quotes"); const moveiData = (link, callBack) => { const xhr = new XMLHttpRequest(); xhr.addEventListener("readystatechange", () => { if (xhr.readyState === 4 && xhr.status == 200) { } else if (xhr.readyState === 4) { callBack("could not fetch data"); } }); xhr.open("GET", link); xhr.send(); }; moveiData(url, (response) => { console.log(response); });