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

调用API返回的文本无法追加到HTML元素,显示Promise对象如何解决

问题原因

  • 所有async关键字修饰的函数默认返回Promise对象,你直接调用getDadJoke()没有等待异步请求完成,拿到的只是处于pending状态的Promise实例,赋值给innerText就会显示[object Promise]
  • 异步请求的结果必须通过await或者.then()的方式才能拿到最终返回值

修复方案

只要把createJoke函数也修改为异步函数,等待getDadJoke()返回结果后再赋值给DOM元素即可,修改后的JS代码如下:

//dad joke generator

//getDadJoke async function with axios
const getDadJoke = async () => {
  const headers = { headers: { Accept: "application/json" } };
  const res = await axios.get("https://icanhazdadjoke.com/", headers);
  return `here is the joke: ${res.data.joke}`;
};

//Selected HTML Elements (button and div(the div contains an h1 title and the button to create a joke))
const container = document.querySelector("#container");
const jokeButton = document.querySelector("#btn--joke");
const resetButton = document.querySelector("#btn--reload");

// 把createJoke修改为async异步函数
const createJoke = async () => {
  const newJoke = document.createElement("h2");
  // 等待getDadJoke异步请求完成,拿到最终的笑话文本
  newJoke.innerText = await getDadJoke();
  container.append(newJoke);
};

jokeButton.addEventListener("click", () => {
  createJoke();
  console.log("This works!!");
});

resetButton.addEventListener("click", () => {
  location.reload(true);
});

如果需要兼容特殊场景,也可以用.then()的写法处理返回结果:

const createJoke = () => {
  const newJoke = document.createElement("h2");
  getDadJoke().then(jokeText => {
    newJoke.innerText = jokeText
    container.append(newJoke)
  })
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:48:00