异步等待在反应中返回承诺

Async await is returning promise in react

函数

const GetProfile = async (username) => {
  await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
    console.log(resp.json());
  });
};

为什么我在这样调用函数时得到 Promise { <state>: "pending" } GetProfile("username"); 我该怎么办?

这是 javascript 中的正常 async 功能行为,他们 return 承诺。

在 React 中,您可以将值保持在状态中。

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() 还 returns 一个 Promise,您的 .then() 打电话。

你的情况是:

const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return response.json();

并且因为 json() 函数本身就是一个 Promise(它不是 await'ed),json() 调用的读取是 'Pending' Promise你得到的。

所以要解决这个问题,请尝试:

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 函数中,一个干净的方法是:

const GetProfile = async (username) => {
  const res = await fetch(`${host}/api/v1/getprofile/${username}`);
  const data = await res.json();
  return data;
  });
};

默认 async function always returns 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 之一返回 return resp.json() 才能看到结果。