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

93
Visualizações
Promises not getting resolved

I am running this asynchronous function in my React app -

const getMetaData = async (hashes: any) => {
    console.log({ hashes });
    try {
      const data = hashes.map(async (hash: any) => {
        const url = `http://localhost:3003/user/pinata/getmetadata/${hash}`;
        const metadata = await axios.get(url);
        return metadata.data.response;
      });
      console.log("data1", data);
      const metadata = await Promise.all(data);
      console.log('data2', metadata);
    } catch (error) {
      console.log('getMetaData Error', error);
    }
  };

console.log("data1", data) gives me -

data1 (12) [Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise, Promise]

The problem here is after I do a await Promise.all(data) I don't get data2 anywhere in the console. Maybe because the Promises are not even getting resolved?

Any idea what might be wrong?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It seems that your code works fine when using SWAPI API so it can be that the API you use does not deliver data appropriately. I run the below code to test. Here's a link to codebox to play around with it if you want.

import axios from "axios";

const data = ["people", "planets", "starships"];

const getMetaData = async (hashes) => {
  console.log({ hashes });
  try {
    const data = hashes.map(async (hash) => {
      const url = `https://swapi.dev/api/${hash}`;
      const metadata = await axios.get(url);
      return metadata.data.results;
    });
    console.log("data1", data);
    const metadata = await Promise.all(data);
    console.log("data2", metadata);
  } catch (error) {
    console.log("getMetaData Error", error);
  }
};

getMetaData(data);
about 4 years ago · Juan Pablo Isaza Relatório

0

With this code, it appears the most likely situation is that one of the promises in the loop is not resolving or rejecting. To confirm that, you can log every possible path with more local error handling so you can see exactly what happens to each request. I also added a timeout to the request so you can definitely find out if it's just not giving a response, but you can also see that by just looking at the logging for begin and end of each request in the loop:

function delay(msg, t) {
    return new Promise((resolve, reject)) => {
        setTimeout(() => {
            reject(new Error(msg));
        }), t);
    });
}

const getMetaData = async (hashes: any) => {
    console.log({ hashes });
    try {
        const data = hashes.map(async (hash: any, index: number) => {
            try {
                console.log(`Request: ${index}, hash: ${hash}`);
                const url = `http://localhost:3003/user/pinata/getmetadata/${hash}`;
                const metadata = await axios.get(url);
                console.log(`Request: ${index}, result: ${metadata.data.response}`);
                return metadata.data.response;
            } catch (e) {
                console.log(`Request: ${index} error: `, e);
                throw e;
            }
        });
        console.log("data1", data);
        const metadata = await Promise.all(data.map((p: any, index: number) => {
            return Promise.race(p, delay(`Timeout on request #${index}`, 5000));
        });
        console.log('data2', metadata);
    } catch (error) {
        console.log('getMetaData Error', error);
    }
};

FYI, I don't really know Typescript syntax so if I've made any Typescript mistakes here, you can hopefully see the general idea and fix the syntax.

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