首页 > 解决方案 > 如何在等待完成之前显示加载图标

问题描述

我有一个带有 await fetch 的异步函数。我想向用户显示一个加载图标,直到等待完成,然后显示下一个 div。

                let getOTP = await fetch(url, {
                    method: 'POST',
                    headers: {
                        "Content-Type": "text/plain"     
                    },
                    body: JSON.stringify({
                        "Number": mobileNumber
                    })
                });

                let data = await getOTP.json();
                let errorCode = data.errorCode;
                if (errorCode == 0) {// show next div}

我尝试使用 setTimeout(function (){},5000) 设置为 5 秒(或更多)的函数,但有时需要更长的时间才能收到回复。那么,如何在等待完成之前显示加载图标?

标签: javascriptasync-awaitloading

解决方案


只需在 fetch 之前显示 loader,然后在await.

const fetchButton = document.querySelector('#fetchButton')
const loader = document.querySelector('#loader')
const content = document.querySelector('#content')

function fetchData() {
  // Here should be your api call, I`m using setTimeout here just for async example
  return new Promise(resolve => setTimeout(resolve, 2000, 'my content'))
}

fetchButton.onclick = async function () {
  content.innerHTML = ''

  // Your loader styling, mine is just text that I display and hide
  loader.style.display = 'block'
  const nextContent = await fetchData()
  loader.style.display = 'none'

  content.innerHTML = nextContent
}
<button id="fetchButton">Fetch</button>
<div id="loader" style="display: none">Loading...</div>
<div id="content"></div>


推荐阅读