You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在async异步函数执行完毕前禁用对应的触发按钮

最优实现方案

核心逻辑是在异步请求的全生命周期管控按钮状态,通过finally块保证无论请求成功/失败都能恢复按钮可用性,避免出现按钮永久禁用的异常情况。

完整修改后代码

const FetchButton = document.getElementById("fetch");
const itemDiv = document.getElementById("item-div");
// 存储按钮原始文案,用于加载结束后恢复
const originBtnText = FetchButton.innerText;

const fetchData = async () => {
  // 请求发起前立刻禁用按钮,可修改文案提示加载状态
  FetchButton.disabled = true;
  FetchButton.innerText = "获取中...";

  const randomPokemonId = Math.floor(Math.random() * 898) + 1;
  const URL = `https://pokeapi.co/api/v2/pokemon/${randomPokemonId}`;
  console.log(randomPokemonId);
  try {
    let res = await fetch(URL);
    res = await res.json();
    itemDiv.innerHTML = res.name;
    return res;
  } catch (err) {
    console.log(err);
  } finally {
    // 无论请求结果如何,最终都恢复按钮可用状态
    FetchButton.disabled = false;
    FetchButton.innerText = originBtnText;
  }
};

FetchButton.addEventListener("click", fetchData);

方案优势

  • 状态管控逻辑无遗漏:finally块会在异步流程结束后强制执行,不会因为请求报错、代码异常等问题导致按钮永久禁用
  • 体验优化:新增加载状态文案,用户可直观感知请求正在进行
  • 代码简洁:所有状态恢复逻辑集中在一处,无需在成功、失败分支重复编写
  • 顺带优化了随机ID生成逻辑,原有Math.floor(Math.random() * (1 + 898 - 1))等价于Math.floor(Math.random() * 898) + 1,可读性更高

内容的提问来源于stack exchange,提问作者sneaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 16:06:03