javascript - 如何在等待完成之前显示加载图标
问题描述
我有一个带有 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>
推荐阅读
- flutter - 如何使用 google_sign_in 仅获取电子邮件
- javascript - React 循环发送多个请求并等待
- python - 写 3 个正数并求和
- swift - 如何将多个 UI 分配给一个参数,例如 UILabels 和 UIButtons?
- google-apps-script - 非重复电子邮件 Google 表格脚本 - 运行脚本后防止发送重复电子邮件
- linux - 从 Linux 服务器调用 Windows 服务器上的 VBScript
- javascript - promise.resolve() 和 reject() 中的可接受参数
- ruby-on-rails - 如何在 simple_calendar 上输出任务标题
- node.js - 您如何使用节点 posgres 进行动态插入查询?
- php - password_verify 始终返回 false