控制台日志记录在函数 returns 一个对象时打印一个承诺,但在它不是一个对象时打印数据

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

我有这个函数可以向 api

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

当我在按钮 onClick 处理程序上使用此函数时

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

控制台显示的是承诺而非实际数据

但是当我将 get 函数切换到

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

它没有返回数据周围的对象, 然后通过

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

控制台打印出实际数据。 为什么会这样?我更愿意以第一种方式来做,并为 error 添加一个提取密钥,但这个日志记录问题真的很烦我

第一种方式:

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

请记住 response.json() 本身 return 就是一个承诺。

所以你说 return {data: <Promise>}

第二个之所以有效,是因为您 return 直接在异步函数中执行 promise,

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

当您 return 来自异步函数的 promise 时,get().then(... 会像往常一样解决该 promise,因此您会得到您期望的正确数据。

如果你想做第一种方式,await首先:

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};
};