0

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?

yousoumar
  • 7,434
  • 4
  • 9
  • 33
RoyalBosS
  • 172
  • 8
  • because .json() returns a promise again, your have to await or then the result for printing the resolved – quirimmo Dec 03 '21 at 13:37
  • Whats the solution ? – RoyalBosS Dec 03 '21 at 13:38
  • Does this answer your question? [Trying to implement a SIMPLE promise in Reactjs](https://stackoverflow.com/questions/40029867/trying-to-implement-a-simple-promise-in-reactjs) – Quentin Dec 03 '21 at 13:38
  • `Promise.then()` returns promise, and also `async function` returns promise. There's no way to solve promise globally and completely in javascript. – Bad Dobby Dec 03 '21 at 13:43

4 Answers4

1

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;
  });
};
yousoumar
  • 7,434
  • 4
  • 9
  • 33
0

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])
Erfan
  • 1,327
  • 1
  • 3
  • 10
0

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();
Alserda
  • 2,105
  • 14
  • 24
0

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.

Mario Petrovic
  • 5,868
  • 12
  • 32
  • 54