Home > Back-end >  axios returns promise instead of data
axios returns promise instead of data

Time:05-07

I am querying some data from IPFS using axios, the problem is that after calling the specific api the return value is a promisse from axios.

const getNFTDetail = async (url: any) => {
    const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
    try {
      return await axios.get(urlIPF).then((res) => {
        return res.data;
      });
    } catch (error) {
      console.log(error);
    }
  };

response I get:

enter image description here

is there a way to wait until promisse has been resolved?, as you see I am already using async await on the function call.

CodePudding user response:

just, decide if you use async / await or .then / .catch:

const getNFTDetail = async (url: any) => {
  const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");
  const { data } = await axios.get(urlIPF);
    return data;
};

or

const getNFTDetail = (url: any) => {
  const urlIPF = url.replace("ipfs://", "https://cloudflare-ipfs.com/ipfs/");

  axios.get(urlIPF).then(({data}) => {
    // use your data here
  }).catch((err)=>{
    console.log(err);
  };
};

CodePudding user response:

When you fetch a request, no matter any http client you use, will then return a Promise.

Just use ‘await’ to get a response from your request.

const response = await axios.get(your-url);
const json = await response.json();

To use typescript correctly, type the url a string: ‘(url: string)’ instead of happy ‘any’ type.

  • Related