[英]JavaScript, async await is returning a promise instead of the result
我有以下 function。 为什么我在调用GetProfile("username")
时会收到Promise { <state>: "pending" }
? 我应该怎么办?
const GetProfile = async (username) => {
await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
console.log(resp.json());
});
};
resp.json()
返回一个Promise
这就是你在控制台记录的内容。 它应该在获取实际数据之前解决。 由于您处于async
function 中,因此您可以执行以下操作。 请注意,没有必要拥有这个then
阻止你拥有。
const GetProfile = async (username) => {
const res = await fetch(`${host}/api/v1/getprofile/${username}`);
const data = await res.json();
return data;
});
};
这是 javascript 中的正常async
function 行为,它们返回承诺。
在 React 中,您可以将值保存在 state 中。
const [profile,setProfile]=useState(null)
useEffect(()=> {
const GetProfile = async (username) => {
const profile = await fetch(`${host}/api/v1/getprofile/${username}`).then(resp => resp.json());
setProfile(profile)}
GetProfile(username);
},[username])
因为您在异步调用之后使用.then
,并且resp.json()
还返回一个Promise
,您的 .then .then()
调用没有返回它。
您的情况是:
const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return response.json();
并且因为json()
function 本身是 Promise (它不是await
'ed),所以读取json()
调用是 'Pending' ZA5A3F0F287A448982AAC520CFFE47'
因此,要解决此问题,请尝试:
await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => resp.json())
或者
const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return await response.json();
默认情况下async
function 总是返回 promise 。 您需要做的是使用await
执行它,您可以提取结果,或者将其与then
链接并继续。
我用await
做了一个例子:
const GetProfile = async (username) => {
await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
console.log(resp.json());
return resp.json()
});
};
const result = await GetProfile()
console.log(result);
笔记:
您需要从then
之一返回resp.json()
以查看结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.