javascript - 如何在原生 JavaScript 中异步管理状态
问题描述
我正在获取数据
const getAllCountries = async () => {
try {
const response = await axios.get(`/api/cities-list`);
return response.data;
} catch (err) {
return err.response;
}
}
const allCountries = await getAllCountries();
使用 vanilla JS,我想为较慢的连接添加某种加载状态(或者如果 api 需要比正常时间更长的时间来响应)。我正在这样做
const getAllCountries = async () => {
try {
document.querySelector('#results').innerHTML = 'Loading'; // Displaying 'Loading' text
const response = await axios.get(`/api/cities-list`);
document.querySelector('#results').innerHTML = null;
return response.data;
} catch (err) {
return err.response;
}
}
const allCountries = await getAllCountries();
这在慢速连接上工作正常,但在较快的连接上,“加载”文本会出现一瞬间,然后消失,这是预期的。
如何添加某种延迟(例如setTimeout
)以使加载状态仅在 1 秒后显示(例如)?如果在 1 秒之前返回数据,则不显示加载状态。换句话说,快速连接的用户将看不到加载文本。
解决方案
如果您response
在范围内提升得更高,您可以在超时内访问它
const getAllCountries = async () => {
try {
let response;
setTimeout(() => {
if (!response) {
document.querySelector('#results').innerHTML = 'Loading'; // Displaying 'Loading' text
}
}, 1000)
response = await axios.get(`/api/cities-list`);
document.querySelector('#results').innerHTML = null;
return response.data;
} catch (err) {
return err.response;
}
}
推荐阅读
- ruby-on-rails - 我在一个事务中创建和销毁一个 ActiveStorage 文件。如何阻止排队的 AnalyzeJob 运行?
- amazon-sns - 通过 AWS SNS 将日志摄取到 Splunk
- python - python如何检查元组是否包含列表中的任何内容?
- regex - REGEX_REPLACE 无法正常工作 spark、hive 和 scala
- php - 将字符串覆盖到数组
- git - 将提交移动到另一个分支
- ios - 从 SpreadsheetView 检索 TextField 用户条目
- for-loop - 如何将整个关键字传递给 for 循环变量 | linux |
- python - python中是否有适当的方法来限制具有模式匹配的numpy数组的形状?
- angular - 角度,文件上传