By Noxxxx from https://www.noxxxx.com/?post_type=post&p=1843
欢迎分享与聚合,尊重版权,可以联系授权
在前端请求这个逻辑中,往往会出现一种尴尬😅 的情况:
伪代码:
function getList () {
showLoading() // 加载 loading
request().then(res => {
hideLoading() // 隐藏 loading
})
}
getList()
通常来说这个逻辑没有错误,但是实际效果上会出现请求加载很快,导致 loading 效果出现转瞬即逝的视觉停留。
可以点击「普通请求」:
See the Pen Loading tips by hjoker (@hjoker) on CodePen.
优化后的代码:
const delay = 200;
const duration = 500;
const timeout = (duration) => {
return new Promise(resolve => {
setTimeout(() => resolve(null), duration);
});
};
const performFetch = (fn, message = '', showLoading = true) => {
return new Promise((resolve, reject) => {
const p = fn();
Promise.race([ p, timeout(delay) ]).then((result) => {
if (!result) {
// 下拉刷新的场景不需要 loading
if (showLoading) {
// show();
}
Promise.all([ p, timeout(duration) ]).then((data) => {
// showLoading && hide();
resolve(data[0]);
});
} else {
resolve(result);
}
});
});
};
核心方法就是通过 Promise.race
来判断请求是否超过设定的容忍阈值,一旦超过等待值,就开始展示 loading
,loading
展示的最小时间通过 timeout
方法来实现。