简体   繁体   English

axios 返回 promise 而不是数据

[英]axios returns promise instead of data

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.我正在使用 axios 从 IPFS 查询一些数据,问题是在调用特定的 api 之后,返回值是来自 axios 的承诺。

const getNFTDetail = async (url: string) => {
    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:我得到的回应:

在此处输入图像描述

is there a way to wait until promisse has been resolved?, as you see I am already using async await on the function call.有没有办法等到 promise 得到解决?正如您所见,我已经在 function 调用中使用异步等待。

just, decide if you use async / await or .then /.catch :只是,决定你是使用async / await还是.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);
  };
};

When you fetch a request, no matter any http client you use, will then return a Promise.当您获取请求时,无论您使用任何 http 客户端,都会返回一个 Promise。

Just use await to get a response from your request.只需使用await即可从您的请求中获得响应。

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.要正确使用 typescript,请键入 url 字符串: (url: string)而不是 happy any类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM