Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
I need one async function to wait for another one

I have 2 async functions - one gets ids of towns, and the second one takes these ids and gets {towns} objects. I am importing an API which is also async.

The first function works fine, but the second one returns

LOG catchTowns [Error: Not found]

code:

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)
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I don't know how you are handling state nor if you are using class or functional components so I'll just give an example how I'd do it using a functional component and hooks.

The idcka promise should return something and store its state at some point, maybe just there or using redux. I'll just use the state hook here.

const [idckaValue, setIdckaValue] = useState([])

// call idcka promise and store result by using the above setter setIdckaValue()...

Then, use an effect hook to call the second promise when idckaValue has changed.

useEffect(() => {
    // call towns promise...
}, [idckaValue])

This way, we ensure that the towns promise only runs when idckaValue changes.

And finally here's some documentation about hooks.


So wrapping up now using an effect hook to the first function too.

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.
    );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda