To optimize the user experience , We want interfaces that return data slowly , Can display a loading animation , But we don't want to show this animation when the data return is relatively fast . Here is a way , To solve this problem
The core of the method is Promise.race(), In a brief review Promise.race Usage method ,Promise.race(iterable) Method takes an iteratable object as a parameter , Return to one promise. One of the iterators promise To settle or refuse , Back to promise Will solve or refuse , That is to say, whoever has the response first will return the result of who .
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'promise 1 resolved');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(reject, 100, 'promise 2 rejected');
});
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 200, 'promise 3 resolved')
});
(async () => {
try {
let result = await Promise.race([promise1, promise2, promise3]);
console.log(result);
} catch (err) {
console.error(err);
}
})();
// Output :promise 2 rejected
// because promise2 First response , So the return is cacth To the reject value Based on this, we have a solution to the problem : By writing a timeout function , To determine whether the interface responds first or timeout The function responds first , If timeout If there is one, it means that it needs to be displayed loading, Otherwise, there is no need to display .
// Simulate network requests
function getUserInfo(user) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("user data!"), Math.floor(900*Math.random()));
});
}
// Analog interface request
function showUserInfo(user) {
return getUserInfo().then(info => {
// Business logic is handled here
console.log(info)
// return Value is used to tell promise.rece() Request completed
return true;
});
}
// loading function
function showSpinner() {
console.log("please wait...")
}
// Delay function
function timeout(delay, result) {
return new Promise(resolve => {
setTimeout(() => resolve(result), delay);
});
}
// If 300ms after timeout No response , Show loading
Promise.race([showUserInfo(), timeout(300)]).then(displayed => {
if (!displayed) showSpinner();
});Be careful : showUserInfo A function must have a return value , To tell promise.rece() Request completed
How to request data , Display load animation First appeared in Juxiang station , If it helps you , Don't forget to praise and support









