我正在尋找一種方法來禁用我的 "獲取資料 "按鈕,直到資料被獲取為止。 目前我有這樣的代碼:
const FetchButton = document. getElementById("fetch") 。
const itemDiv = document.getElementById("item-div") 。
const fetchData = async ( ) => {
const randomPokemonId = Math.floor(Math)。 random() * (1 898 - 1) 。)
const URL = `https://pokeapi.co/api/v2/pokemon/${randomPokemonId}`。
console.log(隨機精靈ID)。
try {
let res = await fetch(URL)。
res = await res.json()。
itemDiv.innerHTML = res.name;
return res;
} catch (err) {
console.log(err)。
}
};
FetchButton.addEventListener("click"/span>, fetchData)。
我怎樣才能以最好的方式完成這個任務?
提前感謝您!
CodePudding
fetchData已經是一個異步函式,所以應該回傳一個承諾。與其直接呼叫這個函式,不如將其封裝在一個呼叫它的函式中,并在其中添加一個then:
const fetchButtonClick = ()/span> => {
FetchButton.disabled = true
fetchData().then(
() => FetchButton.disabled = false)
)
}
uj5u.com熱心網友回復:
有一個封裝器。
const FetchButton =document. getElementById("fetch") 。
const itemDiv = document.getElementById("item-div") 。
const getPokemon = async ( ) => {
FetchButton.disabled = true;
const pokemon = await fetchData() 。
if(!!pokemon){
itemDiv.innerHTML = pokemon.name。
}
FetchButton.disabled = false;
}
const fetchData = async ( ) => {
const randomPokemonId = Math.floor(Math)。 random() * (1 898 - 1) 。)
const URL = `https://pokeapi.co/api/v2/pokemon/${randomPokemonId}`。
console.log(隨機精靈ID)。
try {
let res = await fetch(URL)。
res = await res.json()。
return res;
} catch (err) {
console.log(err)。
}
};
FetchButton.addEventListener("click"/span>, getPokemon)。
筆者在這里。https://codepen.io/freedruk/pen/powNbXL
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/318066.html
標籤:
