首页 > 解决方案 > javascript 获取 api 并返回数据以使用它

问题描述

我已经在 javascript 函数中有一个问题axios 来返回有关此的数据,但它已被关闭,我仍在与此作斗争。

但是,我取得了一些进展。

class Api {
  getPin = () => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => this.getResults(json));
  };

  async getResults(data) {
    let pin = await data;
    console.log(pin.id);
  }
}

let api = new Api();

api.getPin();

这将获得 API 调用,我可以对其进行控制台记录(这是在 10 小时后查看此内容:'-() 理想情况下,我想在应用程序的其他地方使用结果

有人可以帮忙吗?我正在为此苦苦挣扎

编辑:

class Api {
  getPin = () => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => this.getResults(json));
  };

  getResults(data) {
    // console.log(data);
    return data;
  }
}

let api = new Api();

let pin = api.getPin();

console.log(pin);

如果我摆脱异步并等待并从函数返回数据,我在尝试控制台日志时会变得不确定。我还缺少什么?

标签: javascriptfetch

解决方案


推荐阅读