Javascript 来自API的数据调用为空

Javascript 来自API的数据调用为空,javascript,rest,Javascript,Rest,我的API调用有问题。当我返回数据时,我得到一个包含数据的空数组。 这是我调用API的代码 function HeadQuartersGet() { var data = []; async function fetchData() { var myHeaders = new Headers(); myHeaders.append("Content-Type", "application/json"); var requestOptions = {

我的API调用有问题。当我返回数据时,我得到一个包含数据的空数组。 这是我调用API的代码

function HeadQuartersGet() {
   var data = [];
   async function fetchData() {
      var myHeaders = new Headers();
      myHeaders.append("Content-Type", "application/json");
      var requestOptions = {
         method: 'GET',
         headers: myHeaders,
         redirect: 'follow'
      };
      var json = await fetch(url, requestOptions)
         .then((response) => {
            return response.json();
         })
         .then((result) => {
            console.log(result);
         });
      data = JSON.stringify(json);
   }
   fetchData();
   console.log(data);
   return [data];
};

我的数据日志是空的。我需要做什么才能从结果中获取数据,因为结果日志中有我的数据。

fetchData
函数中,返回一个json承诺,因为这是第一次执行fetch时返回的,在调用
fetchData
Inside
headquartsGet
后,请评估您对实际数据的承诺并将其记录下来

 async function HeadQuartersGet() {
  let data = [];
  async function fetchData() {
    const myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    const requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
    };
    return await fetch(url, requestOptions);

  }
  data = await fetchData();
  console.log(data);
  return [data];
};

由于JavaScript的异步行为,您的数据将为空。问题是,您对如何使用async/await有点困惑。当存在
async/await
时,无需使用承诺(
.then(),.catch()
)。您的响应数据将被分配给您创建的json变量。