Tengo 2 funciones asíncronas: una obtiene identificaciones de ciudades y la segunda toma estas identificaciones y obtiene objetos {ciudades}. Estoy importando una API que también es asíncrona.
La primera función funciona bien, pero la segunda regresa
LOG catchTowns [Error: No encontrado]
código:
import { getTown, getTownIds } from "./api/towns" //getting IDs from API const getTownIdsAsync = async () => { const asyncids = await getTownIds() return(asyncids.ids) } let idcka = new Promise((resolve, reject) => { resolve(getTownIdsAsync()) }) .then(result => { idcka = result for(i=0; i < idcka.length; i++){ } }) .catch(err => { console.log('catchIdcka', err) }) //getting Towns from API const getTownsByIdsAsync = async (ajdycka) => { const asyncTowns = await getTown(ajdycka) return(asyncTowns) } let towns = new Promise((resolve, reject) => { resolve(getTownsByIdsAsync()) }) .then(result => { towns = result console.log(towns) }) .catch(err => { console.log('catchTowns', err) })No sé cómo está manejando el estado ni si está usando clase o componentes funcionales, así que solo daré un ejemplo de cómo lo haría usando un componente funcional y ganchos.
La promesa idcka debería devolver algo y almacenar su estado en algún momento, tal vez solo allí o usando redux. Solo usaré el gancho de estado aquí.
const [idckaValue, setIdckaValue] = useState([]) // call idcka promise and store result by using the above setter setIdckaValue()... Luego, use un gancho de efecto para llamar a la segunda promesa cuando idckaValue haya cambiado.
useEffect(() => { // call towns promise... }, [idckaValue]) De esta manera, nos aseguramos de que la promesa de las towns solo se ejecute cuando cambie idckaValue .
Y finalmente aquí hay algo de documentación sobre ganchos .
Así que terminando ahora usando un gancho de efecto para la primera función también.
import React, { useState, useEffect } from 'react'; function Example() { // The state hook to store idcka value, I'm assuming it's an array here. const [idckaValue, setIdckaValue] = useState([]); // Your getTownIdsAsync function. const getTownIdsAsync = async () => { const asyncids = await getTownIds() return(asyncids.ids) } // Your getTownsByIdsAsync function. const getTownsByIdsAsync = async (ajdycka) => { const asyncTowns = await getTown(ajdycka) return(asyncTowns) } // This hook will only run once because its second argument is an empty array. useEffect(() => { // Getting IDs from API. getTownIdsAsync() .then(result => { // Let's assume you do something with the data and that the result of it is an array. setIdckaValue(result) }) .catch(error => { console.log('catchIdcka', error) }) }, []); // This hook will only run every time idckaValue changes, note its second argument value. useEffect(() => { // Getting Towns from API getTownsByIdsAsync() .then(result => { // Then you do what you want with result, maybe store it in state and then use it in the render? console.log(towns) }) .catch(error => { console.log('catchTowns', error) }) }, [idckaValue]); return ( // Your render. ); }