Using Async-Await for API onload



我一直在做这个小的hangman游戏项目。

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

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

是否有一种方法来使用async-await,以便它可以等待onload和看起来干净?

下面的代码片段将不会运行,因为这只是部分代码,我不想把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函数并使用fetchAPI来发出请求。它应该是这样的

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

最新更新