簡體   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