我一直在做一个小小的绞刑者游戏项目。
我添加了一个api来获取一个随机单词数组,但是当我在request.onload外部调用它时,该数组不会加载。函数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();
发布于 2021-03-06 09:10:30
由于displayWord需要appArr,请考虑将其设置为async函数并使用fetch应用编程接口发出请求。所以它应该看起来像这样。
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块中,这样如果您的请求失败,您可以在控制台中看到错误
https://stackoverflow.com/questions/66501153
复制相似问题