gpt4 book ai didi

javascript - 如何显示加载图标直到等待完成

转载 作者:行者123 更新时间:2023-11-29 15:07:11 26 4
gpt4 key购买 nike

我有一个带有 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 秒(或更多),但有时需要更长时间才能收到回复。那么,如何在等待完成之前显示加载图标?

最佳答案

只是在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>

关于javascript - 如何显示加载图标直到等待完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58820229/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com