【问题标题】:Fetch returns undefined when assigning response to global variable [duplicate]将响应分配给全局变量时,获取返回未定义[重复]
【发布时间】:2019-10-10 11:04:03
【问题描述】:

我正在尝试将来自 fetch api 调用的响应存储在 gloval 变量中。但是,我存储结果的变量返回未定义。

我尝试使用 async/await 来解决这个问题,但它似乎对这种情况没有帮助。我似乎达到了返回未决承诺的状态,但这不是预期的结果。

var obj;

async function getEmails() {

    let url = "https://api2.frontapp.com/inboxes/xxxxxx/conversations?limit=50";

    return fetch(url, {
    body: undefined,
    method: 'GET',
    headers: {
        'Host': 'api2.frontapp.com',
        'Authorization': 'Bearer xxxxxx',
        "Accept": "application/json",
    }
    })
    .then(res => res.json())
    .then(response => {
        obj = response;
    })
}

getEmails();
console.log(obj);

我希望 obj 返回 fetch 的 json 数据,但它却返回 undefined。

【问题讨论】:

  • 这是异步调用 .then(response => { obj = response; console.log(obj) })
  • @Code-EZ 我已经有那行了。我想在程序的其他地方使用全局变量,但它仍然未定义。

标签: javascript api promise fetch


【解决方案1】:

问题是您试图在请求完成之前读取响应。 试试这个:

getEmails().then(() => {
  console.log(obj);
});

或者,使用await 关键字:

(async () => {
  var obj;

  async function getEmails() {

      let url = "https://api2.frontapp.com/inboxes/xxxxxx/conversations?limit=50";

      return fetch(url, {
      body: undefined,
      method: 'GET',
      headers: {
          'Host': 'api2.frontapp.com',
          'Authorization': 'Bearer xxxxxx',
          "Accept": "application/json",
      }
      })
      .then(res => res.json())
      .then(response => {
          obj = response;
      })
  }

  await getEmails();
  console.log(obj);
})();

【讨论】:

  • 但是我希望能够将 getEmails 返回的 json 存储在变量 obj 中。
  • getEmails 将 json 存储到 obj 变量中,但您无法确定它何时会发生,因为它是一个异步操作。如果您愿意,可以使用 await 关键字...我会更新我的答案
  • 我对这个解决方案的问题是该函数会在自调用时立即运行,这不是我想要的。没有其他方法可以在全球范围内存储数据吗?
  • @danny03 您目前所做的确实将其存储在全球范围内。但在数据存在之前,您无法访问数据。
  • @KevinB 那么,一旦我确定数据确实存在,我该如何访问这些数据呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-19
  • 2016-05-13
  • 1970-01-01
  • 2017-01-16
  • 2013-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多