vaibhav deep
vaibhav deep

Reputation: 835

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.

Upvotes: 2

Views: 146

Answers (2)

jfriend00
jfriend00

Reputation: 707158

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.

Upvotes: 0

akds
akds

Reputation: 681

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);

Upvotes: 1

Related Questions