He tenido un problema con la API de codificación geográfica inversa proporcionada por TomTom , donde recibo 429 respuestas porque estoy asignando más de 72 objetos de latitud y longitud a la API.
Así que decidí intentar hacer una función que esperara 5 segundos antes de disparar otra solicitud; Como TomTom aconseja 5 segundos entre solicitudes.
Pensé que era totalmente kosher (como en mi función a continuación) llamar a una función, (como en mi caso) llamar a Topography.getTopography(latLng) y then llamar, puedo tomar ese resultado y enviarlo al TomTom solicitud. ¿Esto esta mal? ¿O es mi setTimeout?
Aquí está mi función
async function getTopographyData(latLang) { const retryTimes = 5; let counter = 0; var newObj = {}; Topography.getTopography(latLang, options) .then((results) => { newObj.topography = results; newObj.latlng = latLang; return newObj; }) .then(async (newObj) => { var { lat, lng } = newObj.latlng; let result = await axios.get( `https://api.tomtom.com/search/2/reverseGeocode/crossStreet/${lat},${lng}.json?limit=1&spatialKeys=false&radius=10000&allowFreeformNewLine=false&view=Unified&key=${process.env.TOM_TOM_API}` ); var { addresses } = result?.data; var { address, position } = addresses[0]; var [lat, lng] = position.split(",").map((p) => +p); newObj = { ...newObj, latlng: { lat, lng }, address, }; dispatch({ type: "setTopographyData", payload: newObj }); }) .catch(function (error) { if ( (error.response?.status == 403 || error.response?.status == 429) && counter < retryTimes ) { counter++; return new Promise(function (resolve, reject) { setTimeout(function () { resolve(getTopographyData(counter)); }, 5000); }); } else { console.log("error", error); } }); }Cualquier ayuda sería apreciada.
Actualice mientras funciona la solución de num8er, creo que debe haber un problema con TomTom, ya que se detiene en 45 (obteniendo una búsqueda de GeoCode inverso para 45 marcadores de objetos latlang) y escupe errores en la consola. Además, cuando hago clic en el enlace en la consola, ¿puedo ver la respuesta en el navegador?
¿Qué tal refactorizarlo con un ciclo regular con pausa y pausa para que el código sea más legible?
async function getTopographyData(latLng) { const retryTimes = 5; const topographyData = { latlng: latLng, address: null, }; const pause = (ms) => new Promise(resolve => setTimeout(resolve, ms)); for (let counter = 1, canRetry = false; counter <= retryTimes; counter++) { try { const topography = await Topography.getTopography(latLng, options); topographyData.topography = topography; const { lat, lng } = topographyData.latlng; const response = await axios.get( `https://api.tomtom.com/search/2/reverseGeocode/crossStreet/${lat},${lng}.json?limit=1&spatialKeys=false&radius=10000&allowFreeformNewLine=false&view=Unified&key=${process.env.TOM_TOM_API}` ); if (response?.data) { const { addresses } = response.data; const { address, position } = addresses[0]; const [lat, lng] = position.split(",").map((p) => +p); topographyData.address = address; topographyData.latlng = {lat, lng}; } dispatch({ type: "setTopographyData", payload: topographyData }); } catch (error) { console.error(error); canRetry = [403, 429].includes(error.response?.status); } if (!canRetry) { break; } await pause(5000); } }