簡體   English   中英

axios 返回 promise 而不是數據

[英]axios returns promise instead of data

我正在使用 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);
    }
  };

我得到的回應:

在此處輸入圖像描述

有沒有辦法等到 promise 得到解決?正如您所見,我已經在 function 調用中使用異步等待。

只是,決定你是使用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;
};

或者

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

當您獲取請求時,無論您使用任何 http 客戶端,都會返回一個 Promise。

只需使用await即可從您的請求中獲得響應。

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

要正確使用 typescript,請鍵入 url 字符串: (url: string)而不是 happy any類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM