Home > Blockchain >  Async await is returning promise in react
Async await is returning promise in react

Time:12-04

Function

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

Why am i getting Promise { <state>: "pending" } on calling function like this GetProfile("username");

What should i do? Thanks in Advance!

CodePudding user response:

Since you are in an async function, a clean way to do this is :

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

CodePudding user response:

That's normal async function behavior in javascript, they return promises.

In React, you can keep the value in a 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])

CodePudding user response:

By default async function always returns promise. What you need to do is to execute it with await and you can extract the result, or chain it with then and move on.

I made an example with 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);

NOTE:
You need to return resp.json() back from one of thens to see the result.

CodePudding user response:

Because you're using .then after your async call, and resp.json() also returns a Promise which isn't being returned by your .then() call.

What happens in your case is:

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

And because the json() function is a Promise itself (which isn't await'ed), the read of the json() call is the 'Pending' Promise that you're getting.

So to solve this, try either:

await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => resp.json())

or

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

return await response.json();
  • Related