繁体   English   中英

对 API onload 使用 Async-Await

[英]Using Async-Await for API onload

我一直在做这个小刽子手游戏项目。

我添加了一个 api 来抓取一个随机单词数组,但是当我在request.onload之外调用它时,该数组没有加载。 function displayWord()request.onload之外并使用apiArr 当我console.log(apiArr)它是空的,因为它没有等待 api 获取数组的数据。

我想我可以移动 request.onload 中的所有内容,但我觉得那样看起来会很乱。

有没有办法使用 async-await 来等待加载并看起来很干净?

下面的代码片段将不会运行,因为这只是一些部分代码,我不想公开 api 密钥,但我希望它对这个概念有所帮助。

 let apiArr= []; //making a request to get word array let request = new XMLHttpRequest(); request.open('GET', apiURL); request.responseType = 'json'; request.send(); request.onload = function() { const wordArr = request.response; //taking the word array and adding each word to the empty apiArr. for(let i = 0; i < wordArr.length; i++) { let newWordArr = wordArr[i].word; console.log(newWordArr); apiArr.push(newWordArr); } } //If I try to use the apiArr anywhere other than inside the request.onload, the array loads as an empty array instead of waiting for the resquest to fill it out. //I have a function called displayWord that uses apiArr ( i did not put the whole this b/c its long. // How can I make it so it waits for the api request using async/await? displayWord();

由于displayWord需要appArr ,请考虑将其设为async function 并使用fetch API 发出请求。 所以它应该看起来像这样。

async function displayWord() {
  let appArr;
  try {
     appArr = await fetch(apiURL).then(res => res.json());
     // do stuff with your  appArr here
  } catch(err) {
    console.error(err)
  }
}

displayWord();

我将它包装在try/catch块中,这样如果您的请求失败,您可以在控制台中看到错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM