Skip to content
Advertisement

console logging prints a promise when function returns an object but prints the data when it is not an object

I have this function that makes a get request to an api

const get = async (endpoint: string): Promise<object> => {
    const response: Response = await fetch(`${process.env.PROXY}/${endpoint}`, {
      method: "GET",
    });
    return {data: response.json() as object};
};

When I use this function on a buttons onClick handler

onClick={() => {
            get(
              `apiroute`
            ).then((data: object) => {
              console.log("Retuned data", data.data);
            });
          }}

The console shows an a promise not the actual data

but when I switch my get function to

const get = async (endpoint: string): Promise<object> => {
    const response: Response = await fetch(`${process.env.PROXY}/${endpoint}`, {
      method: "GET",
    });
    return response.json() as object
};

where it isn’t returning an object around the data, then access the data by

onClick={() => {
            get(
              `apiroute`
            ).then((data: object) => {
              console.log("Retuned data", data);
            });
          }}

the console prints out the actual data. Why does this happen? I would much prefer to do it the first way and add an extract key for error but this logging issue is really annoying me

Advertisement

Answer

In the first way:

const get = async (endpoint: string): Promise<object> => {
    const response: Response = await fetch(`${process.env.PROXY}/${endpoint}`, {
      method: "GET",
    });
    return {data: response.json() as object};
};

keep in mind that response.json() itself returns a promise.

So you’re saying return {data: <Promise>}.

The reason that the second one works is because you’re returning the promise directly in an async function,

const get = async (endpoint: string): Promise<object> => {
    const response: Response = await fetch(`${process.env.PROXY}/${endpoint}`, {
      method: "GET",
    });
    return response.json();
};

When you return a promise from an Async function, get().then(... resolves the promise like normal, so you’re getting the proper data you expect out.

If you want to do the first way, await it first:

const get = async (endpoint: string): Promise<object> => {
    const response: Response = await fetch(`${process.env.PROXY}/${endpoint}`, {
      method: "GET",
    });
    const data = await response.json();
    return {data: data};
};
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement