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

如何将async异步函数获取的数据存入全局变量并在外部调用?

解决方法

你遇到的核心是异步代码执行时序问题,不用硬写冗长的.then链式调用,用async/await的语法糖就能写出非常清晰的逻辑:

  1. 首先修改getData函数,直接返回结果,避免使用全局变量造成的时序混乱问题:
async function getData() {
    const response = await fetch('https://type.fit/api/quotes');
    const data = await response.json();
    // 数组取值是同步操作,不需要加await
    const randomItem = data[Math.floor(Math.random() * data.length)];
    return {
        quote: randomItem.text,
        author: randomItem.author
    }
}
  1. 单独编写DOM更新函数,和数据请求逻辑解耦:
function renderQuote(quote, author) {
    // 替换为你页面上对应的名言、作者DOM元素选择器
    document.querySelector('.quote-content').innerText = quote;
    document.querySelector('.quote-author').innerText = author || '佚名';
}
  1. 给按钮绑定异步点击处理函数,直接用await拿到请求结果后调用渲染函数即可:
async function handleChangeQuote() {
    const { quote, author } = await getData();
    renderQuote(quote, author);
}

// 绑定到按钮,也可以直接在HTML的button标签写 onclick="handleChangeQuote()"
document.querySelector('#change-quote-btn').addEventListener('click', handleChangeQuote);

关于你提到的.then的疑问

.then确实会返回一个新的Promise实例,所以支持链式调用,但async/await本身就是为了优化异步代码写法设计的语法糖,完全可以替换掉冗长的链式调用,让代码结构更清晰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:30:02