将响应分配给全局变量时,Fetch 返回未定义[重复]

问题描述 投票:0回答:1

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

我尝试使用 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。

javascript promise fetch-api
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.