当前位置:网站首页>How to display loading animation when requesting data

How to display loading animation when requesting data

2022-06-22 05:00:00 wmui

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
原网站

版权声明
本文为[wmui]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221023246830.html