SoFunction
Updated on 2025-04-07

How long does it take to request an instance of at least if the implementation of ES6 is used

1. Background

We all know that ajax request can add a timeout, which means the maximum time to request. If this time exceeds this time, an error will be reported directly. This is how long it takes to request at most. What I have to do now is how long it takes to request at least before the subsequent logic can be executed.

For example, if an ajax request x milliseconds is executed, but I want it to execute for at least 1 second, then we will think like this: After ajax is completed, 1. If x<1s, then we first setTimeout => 1s - x, and then perform subsequent operations. 2 If x>=1s, then we directly perform the subsequent operations. Thinking about it, this is so cumbersome. We also need to record the start time in the front and the end time in the back, and then we can get x. . . .

Or variable flag, set flag in ajax, setTimeout and other methods are all very cumbersome,

2、Solution

Now there is an ES6, which is very suitable for solving such problems. Just like this ([ajaxPromise(), waitPromise(1s)]).then(()=> at least 1s was executed). . .

What if multiple ajax (promise) are executed in order, but the total time is at least 1s? Then use one Promise to wrap multiple ajaxes. Then ([ajaxPromiseAll(), waitPromise(1s)]).then(()=> at least 1s was executed). . .

3. The explanation is very abstract, examples are evidence

This example is like this. There is a red envelope opened in WeChat. When we click to open, the word will at least be completely flipped. We assume that the complete time will take 1 second. If we directly click on the opening, we immediately request ajax and immediately open the red envelope when ajax is completed. The time here may be less than 1s, so we cannot complete it. If the request is greater than 1s, let it flip until the request is completed. So in order to solve this problem, we need to use the above technology.

The reference code is as follows (tested under the latest version of Chrome):

/ ajaxsimulationA
const funcA = async () =&gt;
 new Promise(resovel =&gt; {
  setTimeout(() =&gt; {
   ("done A");
   resovel("func A");
  }, 400);
 });

Because async and await are more comfortable to use than Promise, I used these two syntax sugar to write, and used setTimeout to simulate ajax request. Ajax simulation A and ajax simulation B have an order relationship. For example, first check whether the person still has a chance to open a red envelope, and then request to open the red envelope to get a random red envelope amount.

The above example of how long it takes to request at least for the implementation of ES6 is all the content I have shared with you. I hope you can give you a reference and I hope you can support me more.