[英]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.