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

neskvpey  于 2021-09-23  发布在  Java
关注(0)|答案(1)|浏览(434)

我有一个函数,它向api发出get请求

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

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

  1. onClick={() => {
  2. get(
  3. `apiroute`
  4. ).then((data: object) => {
  5. console.log("Retuned data", data.data);
  6. });
  7. }}

控制台显示的是承诺,而不是实际数据
但是当我将get函数切换到

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

如果不返回数据周围的对象,则通过

  1. onClick={() => {
  2. get(
  3. `apiroute`
  4. ).then((data: object) => {
  5. console.log("Retuned data", data);
  6. });
  7. }}

控制台打印出实际数据。为什么会发生这种情况?我更喜欢用第一种方法,为它添加一个提取键 error 但是这个日志问题真的让我很恼火

8xiog9wr

8xiog9wr1#

首先:

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

记住 response.json() 它本身就是一种承诺。
你是说 return {data: <Promise>} .
第二种方法之所以有效,是因为您直接在异步函数中返回承诺,

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

当您从异步函数返回承诺时, get().then(... 像正常情况一样解决承诺,因此您可以获得预期的正确数据。
如果你想走第一条路, await 它首先:

  1. const get = async (endpoint: string): Promise<object> => {
  2. const response: Response = await fetch(`${process.env.PROXY}/${endpoint}`, {
  3. method: "GET",
  4. });
  5. const data = await response.json();
  6. return {data: data};
  7. };
展开查看全部

相关问题