首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对API onload使用Async-Await

对API onload使用Async-Await
EN

Stack Overflow用户
提问于 2021-03-06 08:15:23
回答 1查看 64关注 0票数 0

我一直在做一个小小的绞刑者游戏项目。

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

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

有没有一种方法可以使用async-await,这样它就可以等待加载并看起来很干净?

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

代码语言:javascript
复制
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();

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-06 09:10:30

由于displayWord需要appArr,请考虑将其设置为async函数并使用fetch应用编程接口发出请求。所以它应该看起来像这样。

代码语言:javascript
复制
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块中,这样如果您的请求失败,您可以在控制台中看到错误

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66501153

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档