[英]Using Async-Await for API onload
I've been working on this little hangman game project.我一直在做这个小刽子手游戏项目。
I added an api to grab an array of random words, but the array is not loading when I call it outside the request.onload
.我添加了一个 api 来抓取一个随机单词数组,但是当我在
request.onload
之外调用它时,该数组没有加载。 The function displayWord()
is outside request.onload
and uses apiArr
. function
displayWord()
在request.onload
之外并使用apiArr
。 When I console.log(apiArr)
it is empty because it is not waiting for the api to get the data for the array.当我
console.log(apiArr)
它是空的,因为它没有等待 api 获取数组的数据。
I figured I can just move everything inside the request.onload, but I felt like that would look messy.我想我可以移动 request.onload 中的所有内容,但我觉得那样看起来会很乱。
Is there a way to use async-await to so it can wait for the onload and look clean?有没有办法使用 async-await 来等待加载并看起来很干净?
The code snippet below will not run since this is just some partial code and I don't want to put the api key public, but I hope it helps with the concept.下面的代码片段将不会运行,因为这只是一些部分代码,我不想公开 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();
Since displayWord
needs appArr
, consider making it an async
function and using the fetch
API to make the request.由于
displayWord
需要appArr
,请考虑将其设为async
function 并使用fetch
API 发出请求。 So it should look something like this.所以它应该看起来像这样。
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();
I'm wrapping it in a try/catch
block, just so if your request fails you can see the errors in the console我将它包装在
try/catch
块中,这样如果您的请求失败,您可以在控制台中看到错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.