刷新异步请求/与事件侦听器异步

Refreshing async requests/ async with event listener

我想知道如何刷新异步请求。例如,我有这段代码,每次单击按钮时我都希望看到不同的消息。

async function start() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    console.log(data)
    let html = `<p>${data.activity}</p>`
    document.querySelector('button').addEventListener('click', toDo.bind(this, html))
}

function toDo(html) {
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}
    
start()

作为“解决方案”,我这样做了:

document.querySelector('button').addEventListener('click', toDo);
async function toDo() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    let html = `<p>${data.activity}</p>`
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}

不确定这种做法是否合适,因为您可能需要一些时间才能看到结果。就我而言,有轻微的延迟是可以理解的。

如果你不想延迟,你需要在你需要它之​​前获取文本并显示它。基本思想是在页面加载时先加载一个。显示新条目后,获取下一个文本。

function textGen () {

  const updateElem = document.querySelector('.msg');

  let currentText = '';
  let isFetching = false;
  
  
  async function fetchText () {
    isFetching = true;
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    currentText = data.activity;
    isFetching = false;
  }
  
  fetchText();
  
  return {
    addNext: function () {
      if (isFetching) return;
      const html = `<p>${currentText}</p>`;
      updateElem.insertAdjacentHTML('beforeend', html);
      fetchText();
    }
  }
}

const myTextGen = textGen();
document.querySelector("button").addEventListener("click", myTextGen.addNext);
<button>Next</button>
<div class="msg"></div>